UNPKG

@eristack/idempotency

Version:

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

66 lines (65 loc) • 2.08 kB
import { IdempotencyConflictError, IdempotencyRequestMismatchError, hashIdempotencyRequest } from "../chunk-UR7ALJYJ.js"; import { __decorateElement, __decoratorStart, __runInitializers } from "../chunk-CGZBV6BD.js"; // src/nest/index.ts import { Injectable } from "@nestjs/common"; import { from, switchMap } from "rxjs"; var _IdempotencyInterceptor_decorators, _init; _IdempotencyInterceptor_decorators = [Injectable()]; var IdempotencyInterceptor = class { constructor(options) { this.options = options; } options; intercept(context, next) { const req = context.switchToHttp().getRequest(); const header = this.options.header ?? "Idempotency-Key"; const raw = req.headers[header.toLowerCase()]; const key = (Array.isArray(raw) ? raw[0] : raw)?.trim(); if (!key) return next.handle(); const scope = this.options.scopeFromContext?.(context) ?? { scope: `${req.method} ${req.url}` }; return from(hashIdempotencyRequest(req.body)).pipe( switchMap( (requestHash) => from( this.options.guard.runScoped({ scope, key, requestHash, fn: () => new Promise((resolve, reject) => { next.handle().subscribe({ next: (value) => resolve(value), error: (err) => reject(err) }); }) }) ) ) ); } }; _init = __decoratorStart(null); IdempotencyInterceptor = __decorateElement(_init, 0, "IdempotencyInterceptor", _IdempotencyInterceptor_decorators, IdempotencyInterceptor); __runInitializers(_init, 1, IdempotencyInterceptor); function mapIdempotencyError(err) { if (err instanceof IdempotencyConflictError) { return { status: 409, body: { error: err.code, message: err.message, key: err.key } }; } if (err instanceof IdempotencyRequestMismatchError) { return { status: 409, body: { error: err.code, message: err.message, key: err.key } }; } return null; } export { IdempotencyInterceptor, mapIdempotencyError }; //# sourceMappingURL=index.js.map