Interceptors
Wire @axiljs/decorator metadata into real behaviour with wire() and wireAll(): audit events, retries with backoff, per-attempt timeouts and custom interceptors.
On this page14
An interceptor turns one decorator's metadata into behaviour around a method call. @axiljs/runtime ships 26 built-in interceptors and lets you register your own. This page covers wiring, tAudit, tRetry, tTimeout and custom interceptors; Intent verification and Resilience cover the rest.
1import { tAudit, tRetry, tTimeout } from '@axiljs/decorator'
2import { wire } from '@axiljs/runtime'
3
4class Payments {
5 @tAudit({ action: 'payment.charged', compliance: ['PCI-DSS'], includeRequest: true })
6 @tRetry({ attempts: 3, backoff: 'exponential', retryOn: ['TimeoutError', 'ECONNRESET'] })
7 @tTimeout(2000)
8 async charge(id: string, amount: number) {
9 return gateway.charge(id, amount)
10 }
11}
12
13wire(Payments) // or wireAll() once at startupWithout wire() (or wireAll()), the decorators above only record metadata and charge() runs as written.
Wiring
wire(target)
Wraps every decorated method of target that has at least one registered interceptor.
- Pass a class to wire its instance methods (on the prototype) and its static methods.
- Pass a prototype or instance to wire only that object.
- Returns
target, so it can be chained:export const payments = new (wire(Payments))().
wire() is idempotent: calling it twice with the same interceptors does nothing the second time. A subclass inherits its parent's wrapper; wiring the subclass re-wraps the original method, so interceptors never run twice.
Methods without interceptor metadata are left untouched, and so are decorated properties (such as tRedact fields).
wireAll()
Wires every class that has method metadata registered so far, and returns the number of methods newly wired.
1import './services/payments.js'
2import './services/users.js'
3import { wireAll } from '@axiljs/runtime'
4
5const wired = wireAll()
6console.log(`wired ${wired} methods`)Warning
Decorators register metadata when the class definition is evaluated. Call wireAll() after every module with decorated classes has been imported; classes imported later are not wired.
unwrap(fn)
Returns the undecorated method behind a wired one, for tests and debugging.
import { unwrap } from '@axiljs/runtime'
const raw = unwrap(Payments.prototype.charge) // no audit, retry or timeoutBuilt-in interceptors
Importing @axiljs/runtime registers all 26 built-in interceptors. Each has an order; lower runs outside higher, regardless of the order the decorators are written in. The three below are the original built-ins; the full order table lists every interceptor.
Note
Changed in 0.3.4: the runtime enforces 26 decorators, up from 3. The new ones are the intent decorators (tPure, tReadOnly, tTenantIsolated, tIdempotent, tSlo, …) and the resilience decorators (tCircuitBreaker, tBulkhead, tCache, tRateLimit, …).
| Decorator | Order | Position | Behaviour |
|---|---|---|---|
tAudit | 100 | outermost | One audit.log event per logical call, after all retries |
tRetry | 200 | middle | retry() from @axiljs/circuit, emits runtime.retry |
tTimeout | 300 | innermost | Per-attempt deadline, rejects with TimeoutError |
For charge() above, the call stack is:
So a timeout applies to each attempt, retries happen inside the audit, and the audit event reports the final outcome once.
tTimeout(ms)
Rejects the call with a TimeoutError when one attempt takes longer than ms. A non-finite or non-positive ms disables the timeout.
1import { TimeoutError } from '@axiljs/runtime'
2
3try {
4 await payments.charge('c_1', 1000)
5} catch (err) {
6 if (err instanceof TimeoutError) {
7 err.name // 'TimeoutError'
8 err.code // 'ETIMEDOUT'
9 err.target // 'Payments.charge'
10 err.timeoutMs // 2000
11 err.message // 'Payments.charge timed out after 2000ms'
12 }
13}Warning
A timeout does not cancel the underlying work. The original promise keeps running; the caller just stops waiting for it. Only time out operations that are safe to abandon, and give remote calls their own client-side timeouts too.
tRetry(options)
Delegates to retry() from @axiljs/circuit.
| Option | Type | Default | Description |
|---|---|---|---|
attempts | number | required | Total attempts, including the first |
delay | number | 1000 | Base delay between attempts, ms |
backoff | 'fixed' | 'linear' | 'exponential' | 'exponential' | How the delay grows |
maxDelay | number | 30000 | Upper bound for the delay, ms |
retryOn | string[] | retry every error | Retry only errors whose name or code is in the list |
Defaults for delay, backoff and maxDelay come from @axiljs/circuit's retry(), which also adds jitter (up to 25% either way) to every delay.
retryOn matches against both error.name and error.code, so you can mix error classes and Node.js system error codes:
1class Inventory {
2 // Retries connection resets and refusals, nothing else
3 @tRetry({ attempts: 3, delay: 50, maxDelay: 500, retryOn: ['ECONNRESET', 'ECONNREFUSED', 'EPIPE'] })
4 @tTimeout(250)
5 async reserve(sku: string, qty: number) { /* ... */ }
6}To retry timeouts, include 'TimeoutError' (the name) or 'ETIMEDOUT' (the code).
Warning
Without retryOn, every error is retried, including validation errors and NotFoundError. Set retryOn on anything that can fail for a non-transient reason, and only retry operations that are safe to repeat.
Tip
Retrying timeouts is often counter-productive: a dependency that is slow because it is overloaded gets slower when every caller asks three times. The high-scale-api template retries connection errors only and maps the remaining TimeoutError to a 504.
tAudit(options)
Emits exactly one audit.log event per logical call (after retries), whether the call succeeds or throws. The original result or error is passed through unchanged.
| Option | Type | Description |
|---|---|---|
action | string | Required. The audit action, e.g. 'payment.charged' |
compliance | string[] | Copied to metadata.compliance, e.g. ['SOC2', 'PCI-DSS'] |
sensitivity | 'low' | 'medium' | 'high' | Copied to metadata.sensitivity |
includeRequest | boolean | Add the method arguments, redacted, as metadata.args |
includeResponse | boolean | Add the return value, redacted, as metadata.result (successful calls only) |
Actor, tenant, request ID, IP and user agent come from the request context. Outside a context (or with no user), the actor is { id: 'system', type: 'system' }.
Events
Both events go to the global event bus from @axiljs/events.
audit.log
The payload has the same shape as @axiljs/cloud's AuditEvent, so an audit sink written for auditLog() also receives events from tAudit:
1{
2 action: 'payment.charged',
3 actor: { id: 'u_42', type: 'user' }, // user.type ?? 'user', or { id: 'system', type: 'system' }
4 tenantId: 'acme', // from the request context
5 requestId: '8f9b6c1e-...',
6 metadata: {
7 target: 'Payments.charge',
8 durationMs: 184,
9 compliance: ['PCI-DSS'], // when set
10 sensitivity: 'high', // when set
11 args: ['c_1', 1000], // includeRequest, redacted
12 result: { /* ... */ } // includeResponse and success, redacted
13 },
14 ip: '203.0.113.7', // req.ip
15 userAgent: 'curl/8.5.0',
16 success: true,
17 error: undefined, // error message when success is false
18 timestamp: '2026-11-11T10:15:00.000Z'
19}args and result go through redact() with its defaults, so tRedact fields are redacted and tSensitive fields are masked.
Subscribe with the event bus. The handler receives an event object whose payload is the audit event:
1import { getGlobalEventBus } from '@axiljs/events'
2
3getGlobalEventBus().on('audit.log', event => {
4 process.stdout.write(JSON.stringify({ type: 'audit', ...(event.payload as Record<string, unknown>) }) + '\n')
5})runtime.retry
Emitted before each retry:
{ target: 'Payments.charge', attempt: 1, delayMs: 1043, error: 'socket hang up' }attempt is the attempt that just failed, delayMs the wait before the next one, and error the failed attempt's message.
1getGlobalEventBus().on('runtime.retry', event => {
2 const { target, attempt, error } = event.payload as { target: string; attempt: number; error: string }
3 console.warn(`retrying ${target} after attempt ${attempt}: ${error}`)
4})Events are emitted without awaiting subscribers. A subscriber that throws produces a process warning and never breaks the business call.
Note
The global event bus is per process. With several workers (see @axiljs/scale), each worker sees only its own audit events, which is fine for writing them to stdout or a database. See multi-process readiness.
Custom interceptors
Register an interceptor for any decorator name with registerInterceptor():
1import { registerInterceptor, wire } from '@axiljs/runtime'
2import type { Interceptor } from '@axiljs/runtime'
3
4const seen = new Map<string, unknown>()
5
6const idempotency: Interceptor<{ key?: string }> = {
7 decorator: 'tIdempotent',
8 order: 150, // inside tAudit, outside tRetry
9 async intercept(invocation, options, proceed) {
10 const key = `${invocation.className}.${invocation.method}:${JSON.stringify(invocation.args)}`
11 if (seen.has(key)) return seen.get(key)
12 const result = await proceed()
13 seen.set(key, result)
14 return result
15 }
16}
17
18registerInterceptor(idempotency)
19wire(Orders) // AFTER registeringNote
The in-memory Map is for illustration only; with several workers or instances, real idempotency needs a shared store.
Warning
Since 0.3.4, tIdempotent has its own built-in interceptor (order 90) with a pluggable store, so registering this example replaces it. Use the built-in in real code; the example only shows the API.
The Interceptor interface:
| Member | Type | Description |
|---|---|---|
decorator | string | Decorator name whose metadata activates it, e.g. 'tIdempotent' |
order | number | Position in the stack; lower runs outside higher |
intercept | (invocation, options, proceed) => Promise<unknown> | Runs around the call |
invocationhastarget(the instance, or the class for static methods),className,methodandargs.optionsis the metadata recorded by the decorator.proceed()continues to the next interceptor or the original method. Call it zero times (short-circuit), once, or several times (astRetrydoes).
Registering an interceptor for a decorator that already has one replaces it. That includes the built-ins, so you can swap tAudit for your own implementation.
Other registry functions:
| Function | Description |
|---|---|
unregisterInterceptor(decorator) | Remove an interceptor; returns true if one was registered |
listInterceptors() | Registered interceptors, sorted by order |
registerBuiltins() | Re-register every built-in interceptor (for example after replacing one in tests) |
The built-ins are also exported individually: auditInterceptor, retryInterceptor and timeoutInterceptor, the intent interceptors (readOnlyInterceptor, idempotentInterceptor, …) and the resilience interceptors (circuitBreakerInterceptor, cacheInterceptor, …). enforcedDecorators() returns { decorator, order } for every registered interceptor, outermost first.
Gotchas
Warning
Wired methods always return a Promise, even if the original method is synchronous. A synchronous throw becomes a rejected promise. Callers must await wired methods.
Warning
Register before wiring. The interceptor stack is resolved when a class is wired. An interceptor registered later only applies to methods wired afterwards. Calling wire() again after registering picks it up, because the new stack differs from the old one.
- Timeouts do not cancel work. See
tTimeoutabove. - No
retryOnmeans retry everything. SeetRetryabove. - Audit events are asynchronous. They are emitted when the call settles but subscribers run afterwards; in tests, wait a tick before asserting on them.
- Decorator order in source does not matter. Only
orderdecides nesting.
Related
Was this page helpful?