Install: @travetto/context
npm install @travetto/context
# or
yarn add @travetto/context
This module provides a wrapper around node's async_hooks to maintain context across async calls. This is generally used for retaining contextual user information at various levels of async flow.
The most common way of utilizing the context, is via the WithAsyncContext decorator. The decorator requires the class it's being used in, to have a AsyncContext member, as it is the source of the contextual information.
The decorator will load the context on invocation, and will keep the context active during the entire asynchronous call chain.
NOTE: while access context properties directly is supported, it is recommended to use AsyncContextValue instead.
Code: Usage of context within a service
import { AsyncContext, WithAsyncContext } from '@travetto/context';
import { Inject } from '@travetto/di';
const NameSymbol = Symbol();
export class ContextAwareService {
@Inject()
context: AsyncContext;
@WithAsyncContext()
async complexOperator(name: string) {
this.context.set(NameSymbol, name);
await this.additionalOp('extra');
await this.finalOp();
}
async additionalOp(additional: string) {
const name = this.context.get(NameSymbol);
this.context.set(NameSymbol, `${name} ${additional}`);
}
async finalOp() {
const name = this.context.get(NameSymbol);
// Use name
return name;
}
}
Within the framework that is a need to access context values, in a type safe fashion. Additionally, we have the requirement to keep the data accesses isolated from other operations. To this end, AsyncContextValue was created to support this use case. This class represents the ability to define a simple read/write contract for a given context field. It also provides some supplemental functionality, e.g., the ability to suppress errors if a context is not initialized.
Code: Source for AsyncContextValue
export class AsyncContextValue<T = unknown> {
constructor(source: StorageSource, config?: ContextConfig);
/**
* Get value
*/
get(): T | undefined;
/**
* Set value
*/
set(value: T | undefined): void;
}
Code: Usage of context value within a service
import { AsyncContext, AsyncContextValue, WithAsyncContext } from '@travetto/context';
import { Inject } from '@travetto/di';
export class ContextValueService {
@Inject()
context: AsyncContext;
#name = new AsyncContextValue<string>(this);
@WithAsyncContext()
async complexOperator(name: string) {
this.#name.set(name);
await this.additionalOp('extra');
await this.finalOp();
}
async additionalOp(additional: string) {
const name = this.#name.get();
this.#name.set(`${name} ${additional}`);
}
async finalOp() {
const name = this.#name.get();
// Use name
return name;
}
}