Async-aware state management, maintaining context across asynchronous calls.
npm install @travetto/contextInstall: @travetto/context
``bash
npm install @travetto/context
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
`typescript
import { type 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.additionalOperation('extra');
await this.finalOperation();
}
async additionalOperation(additional: string) {
const name = this.context.get(NameSymbol);
this.context.set(NameSymbol, ${name} ${additional});
}
async finalOperation() {
const name = this.context.get(NameSymbol);
// Use name
return name;
}
}
`
Code: Source for AsyncContextValue
`typescript`
export class AsyncContextValue
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
`typescript
import { type AsyncContext, AsyncContextValue, WithAsyncContext } from '@travetto/context';
import { Inject } from '@travetto/di';
export class ContextValueService {
@Inject()
context: AsyncContext;
#name = new AsyncContextValue
@WithAsyncContext()
async complexOperator(name: string) {
this.#name.set(name);
await this.additionalOperation('extra');
await this.finalOperation();
}
async additionalOperation(additional: string) {
const name = this.#name.get();
this.#name.set(${name} ${additional});
}
async finalOperation() {
const name = this.#name.get();
// Use name
return name;
}
}
``