UNPKG

@eristack/idempotency

Version:

Idempotency-Key guard with Drizzle store, scoped keys, lease, Express/Nest/client adapters

56 lines (55 loc) • 1.56 kB
import { IdempotencyConflictError, IdempotencyRequestMismatchError, hashIdempotencyRequest } from "../chunk-UR7ALJYJ.js"; import "../chunk-CGZBV6BD.js"; // src/express/index.ts function wrapIdempotentHandler(options, handler) { const header = options.header ?? "Idempotency-Key"; const scopeFromReq = options.scopeFromReq ?? ((req) => ({ scope: `${req.method} ${req.baseUrl}${req.path}` })); return async (req, res, next) => { const rawKey = req.header(header)?.trim(); if (!rawKey) { try { const body = await handler(req, res); if (!res.headersSent) res.status(200).json(body); } catch (err) { next(err); } return; } try { const requestHash = await hashIdempotencyRequest(req.body); const body = await options.guard.runScoped({ scope: scopeFromReq(req), key: rawKey, requestHash, fn: () => handler(req, res) }); if (!res.headersSent) res.status(200).json(body); } catch (err) { if (err instanceof IdempotencyConflictError) { res.status(409).setHeader("Retry-After", "1").json({ error: err.code, message: err.message, key: err.key }); return; } if (err instanceof IdempotencyRequestMismatchError) { res.status(409).json({ error: err.code, message: err.message, key: err.key }); return; } next(err); } }; } export { wrapIdempotentHandler }; //# sourceMappingURL=index.js.map