<!-- This file was generated by @travetto/doc and should not be modified directly -->
<!-- Please modify https://github.com/travetto/travetto/tree/main/module/context/DOC.tsx and execute "npx trv doc" to rebuild -->
# Async Context

## Async-aware state management, maintaining context across asynchronous calls.

**Install: @travetto/context**
```bash
npm install @travetto/context

# or

yarn add @travetto/context
```

This module provides a wrapper around node's [async_hooks](https://nodejs.org/api/async_hooks.html) 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](https://github.com/travetto/travetto/tree/main/module/context/src/decorator.ts#L9) decorator.  The decorator requires the class it's being used in, to have a [AsyncContext](https://github.com/travetto/travetto/tree/main/module/context/src/service.ts#L12) 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](https://github.com/travetto/travetto/tree/main/module/context/src/value.ts#L16) 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;
  }
}
```

## AsyncContextValue
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](https://github.com/travetto/travetto/tree/main/module/context/src/value.ts#L16) 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**
```typescript
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**
```typescript
import { type 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.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;
  }
}
```
