Documentation / @zerotal/cache / index / IdempotencyMiddleware
Class: IdempotencyMiddleware
Defined in: cache/src/IdempotencyMiddleware.ts:103
Idempotency middleware — prevents double-execution of mutating requests.
Clients attach an Idempotency-Key: <uuid> header to any mutating request.
On the first request the handler executes normally and the response is
stored in the cache. All subsequent requests with the same key receive the
stored response without re-running the handler.
Concurrent requests for the same key are coalesced: within a process via an
in-flight map, and across processes via a cross-process lock (the lock
primitive) so only one node executes the handler at a time. Cross-process
locking is on by default and degrades to cache-backed replay when no lock
driver is configured; disable it with useLock: false.
Replayed responses carry an Idempotency-Replay: true header so clients
can distinguish fresh from cached responses.
5xx responses are never cached so transient errors don't permanently suppress retries.
Example
import { IdempotencyMiddleware } from '@zerotal/cache';
import { Cache } from '@zerotal/cache';
// Per-route
Router.post('/api/orders', [OrderController, 'store'], {
middleware: [IdempotencyMiddleware.with({ cache: Cache.instance() })],
});
// Global
app.use([IdempotencyMiddleware.with({ cache: cacheManager, ttl: 48 * 3600 })]);
Extends
Constructors
Constructor
new IdempotencyMiddleware():
IdempotencyMiddleware
Defined in: core/src/middleware/BaseMiddleware.ts:36
Returns
IdempotencyMiddleware
Inherited from
Properties
options
protectedoptions:IdempotencyOptions
Defined in: cache/src/IdempotencyMiddleware.ts:104
Subclasses must declare this with their default option values. TypeScript enforces this at compile time — forgetting it is a type error.
Overrides
Methods
handle()
handle(
http,next):Promise<void|Response>
Defined in: cache/src/IdempotencyMiddleware.ts:117
Parameters
http
next
Returns
Promise<void | Response>
Overrides
with()
staticwith<T,Opts>(this,options): () =>InstanceType<T>
Defined in: core/src/middleware/BaseMiddleware.ts:48
Returns a zero-arg subclass with the given options deep-merged on top of the subclass defaults, usable directly in app.use([...]).
Type Parameters
T
T extends (...args) => BaseMiddleware<any>
Opts
Opts = T extends (...args) => BaseMiddleware<U> ? U : object
Parameters
this
T
options
Partial<Opts>
Returns
() => InstanceType<T>
Inherited from
afterResponse()?
optionalafterResponse(ctx):Promise<void>
Defined in: core/src/middleware/BaseMiddleware.ts:70
Parameters
ctx
Returns
Promise<void>
Inherited from
onError()?
optionalonError(ctx,error):Promise<void>
Defined in: core/src/middleware/BaseMiddleware.ts:71
Parameters
ctx
error
Error
Returns
Promise<void>