UNPKG

@eristack/idempotency

Version:

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

104 lines (100 loc) • 3.4 kB
"use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/express/index.ts var express_exports = {}; __export(express_exports, { wrapIdempotentHandler: () => wrapIdempotentHandler }); module.exports = __toCommonJS(express_exports); // src/core/errors.ts var IdempotencyConflictError = class extends Error { constructor(key) { super(`Idempotency key already in progress: ${key}`); this.key = key; this.name = "IdempotencyConflictError"; } key; code = "IDEMPOTENCY_CONFLICT"; }; var IdempotencyRequestMismatchError = class extends Error { constructor(key) { super(`Idempotency key reused with different request body: ${key}`); this.key = key; this.name = "IdempotencyRequestMismatchError"; } key; code = "IDEMPOTENCY_REQUEST_MISMATCH"; }; // src/core/request-hash.ts async function hashIdempotencyRequest(body) { const text = body === void 0 || body === null ? "" : typeof body === "string" ? body : JSON.stringify(body); const bytes = new TextEncoder().encode(text); const digest = await crypto.subtle.digest("SHA-256", bytes); return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join(""); } // 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); } }; } // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { wrapIdempotentHandler }); //# sourceMappingURL=index.cjs.map