Per-request state
Controllers, guards, interceptors and services are singletons, so nothing that belongs to one request may live in their fields. Per-request data lives on the request context instead. There are three tools for it:
Use the first that fits.
Context keys
createContextKey<T>(name) creates a slot of type T.
A guard or an interceptor fills it, and anything later in the request reads it:
ctx.get(CurrentUser) is typed AuthUser, not AuthUser | undefined. That is right behind a guard that always sets it; on a route where the guard may not have run, use ctx.find.
The name is used in error messages only. Two keys created with the same name are different keys.
The guard that sets this key is built in Authentication with JWT.
Request values
A request value is a class with a resolve(ctx) method, decorated with @RequestValue(). The class is a singleton and can inject() other singletons. ctx.get(TheClass) calls resolve on the first read and returns the stored result for the rest of the request.
A guard and a handler of the same request both ask for it, and the tenant is loaded once:
A request that never asks for the tenant never loads it. That is the difference from a context key: a key is filled by whoever sets it, a request value is computed on demand.
- The type of
ctx.get(X)is the return type ofresolve. Whenresolvereturns a promise, the promise itself is stored, so concurrent readers share one computation. A synchronousresolvestays synchronous. ctx.find(X)computes the value just asctx.get(X)does.ctx.has(X)does not.ctx.set(X, value)fills the slot directly andresolveis not called for that request.ctx.get(X)then returns the plain value, so alwaysawaitthe result of an asynchronous request value.resolvemay read other slots withctx.get(...).- When
resolvethrows synchronously nothing is stored, and the next read calls it again. A returned promise that rejects is stored, and every reader in that request gets the same rejection. - A
resolvethat returns a thenable of another kind, such as a query builder, counts as asynchronous: it is stored as a promise, so it runs once per request. - The class needs a constructor without parameters.
Two request values that await each other are not detected as a cycle; the request waits forever. A cycle between values that read each other synchronously inside resolve is reported with its path: Circular request values: A -> B -> A.
Listing values in a module
A listed value is built while the application initialises. That makes a mistake in it, such as an injected request-scoped service, an error of init() instead of an error of the first request. It is required when the class, or a service behind it, has an asynchronous onServiceInit and resolve is not declared async.
An unlisted value still works in the common cases: when everything it injects is ready by the first read, or when resolve is async.
Releasing a value
A request value may implement dispose(value, ctx). It is called after the response has been sent, or after the client has gone away, for every value computed in that request, in reverse order of computation.
dispose receives the awaited value. It is not called for a value placed with ctx.set. An error it throws is logged, and the other hooks still run.
Once the response has finished, for example in a stream that is still running after its client has gone, a value with a dispose hook can no longer be computed: the read throws, because nothing would release it.
Without decorator syntax, register the class with registerRequestValue(TheClass).
Request-scoped services
A service with scope: InjectableScope.Request is constructed once per request by the DI container. It can inject other request-scoped services, and inject(RequestContextToken) gives it the RequestContext.
A handler, guard or interceptor reaches it through the context:
ctx.use(Token)resolves synchronously. It throws when the service or one of its dependencies has an asynchronousonServiceInit; useawait ctx.resolve(Token)for those.- The first
ctx.use()orctx.resolve()of a request creates its DI scope. A request that calls neither has no scope and pays nothing for one. - The scope is disposed after the response has been sent, which runs
onServiceDestroy. After that pointctx.use()andctx.resolve()throw.
A request-scoped service cannot be injected into a singleton. Controllers, guards, interceptors and request values are singletons, so inject(AuditTrail) in any of them fails at init() with a scope mismatch error that names the path. Reach the service with ctx.use() instead.
Scopes themselves are explained in Scopes.
The requestScopedServices option
Because a request value usually does the same job with less machinery, the application can report or refuse request-scoped services:
The option is checked when a token is first requested, not at init().
Choosing
- Something already computed by a guard or interceptor: a context key.
- Something derived from the request, possibly asynchronous, wanted by some routes only: a request value. Add
disposewhen it holds a resource. - A third-party class that must be constructed per request, or several per-request classes that inject each other and need
onServiceInitandonServiceDestroy: a request-scoped service.
Code that cannot be handed the context at all, such as a logger several calls deep, can read it with currentContext().