Giter Site home page Giter Site logo

nestjs-steroids / async-context Goto Github PK

View Code? Open in Web Editor NEW
44.0 2.0 3.0 641 KB

:link: NestJS Async Context based on async_hooks

License: MIT License

TypeScript 100.00%
nestjs asynchooks nodejs asyncstorage request-context requestid async-context

async-context's Introduction

Async Context

Zero-dependency module for NestJS that allow to track context between async call

Installation

npm install @nestjs-steroids/async-context
yarn add @nestjs-steroids/async-context
pnpm install @nestjs-steroids/async-context

Usage

The first step is to register AsyncContext inside interceptor (or middleware)

src/async-context.interceptor.ts

import { randomUUID } from 'crypto'
import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler
} from '@nestjs/common'
import { AsyncContext } from '@nestjs-steroids/async-context'
import { Observable } from 'rxjs'

@Injectable()
export class AsyncContextInterceptor implements NestInterceptor {
  constructor (private readonly ac: AsyncContext<string, any>) {}

  intercept (context: ExecutionContext, next: CallHandler): Observable<any> {
    this.ac.register() // Important to call .register or .registerCallback (good for middleware)
    this.ac.set('traceId', randomUUID()) // Setting default value traceId
    return next.handle()
  }
}

The second step is to register AsyncContextModule and interceptor inside main module

src/app.module.ts

import { APP_INTERCEPTOR } from '@nestjs/core';
import { Module } from '@nestjs/common';
import { AsyncContextModule } from '@nestjs-steroids/async-context';
import { AsyncContextInterceptor } from './async-context.interceptor';

@Module({
  imports: [
    AsyncContextModule.forRoot()
  ],
  providers: [
    {
      provide: APP_INTERCEPTOR,
      useClass: AsyncContextInterceptor,
    },
  ],
})
export class AppModule {}

The last step is to inject AsyncContext inside controller or service and use it

src/app.controller.ts

import { Controller, Get, Logger } from '@nestjs/common'
import { AppService } from './app.service'
import { AsyncContext } from '@nestjs-steroids/async-context'

@Controller()
export class AppController {
  constructor (
    private readonly appService: AppService,
    private readonly asyncContext: AsyncContext<string, string>,
    private readonly logger: Logger
  ) {}

  @Get()
  getHello (): string {
    this.logger.log('AppController.getHello', this.asyncContext.get('traceId'))
    process.nextTick(() => {
      this.logger.log(
        'AppController.getHello -> nextTick',
        this.asyncContext.get('traceId')
      )
      setTimeout(() => {
        this.logger.log(
          'AppController.getHello -> nextTick -> setTimeout',
          this.asyncContext.get('traceId')
        )
      }, 0)
    })
    return this.appService.getHello()
  }
}

Output example

[Nest] 141168  - 02/01/2022, 11:33:11 PM     LOG [NestFactory] Starting Nest application...
[Nest] 141168  - 02/01/2022, 11:33:11 PM     LOG [InstanceLoader] AsyncContextModule dependencies initialized +47ms
[Nest] 141168  - 02/01/2022, 11:33:11 PM     LOG [InstanceLoader] AppModule dependencies initialized +1ms
[Nest] 141168  - 02/01/2022, 11:33:11 PM     LOG [RoutesResolver] AppController {/}: +12ms
[Nest] 141168  - 02/01/2022, 11:33:11 PM     LOG [RouterExplorer] Mapped {/, GET} route +7ms
[Nest] 141168  - 02/01/2022, 11:33:11 PM     LOG [NestApplication] Nest application successfully started +5ms
[Nest] 141168  - 02/01/2022, 11:33:13 PM     LOG [7398d3ad-c246-4650-8dd0-f8f29238bdd7] AppController.getHello
[Nest] 141168  - 02/01/2022, 11:33:13 PM     LOG [7398d3ad-c246-4650-8dd0-f8f29238bdd7] AppController.getHello -> nextTick
[Nest] 141168  - 02/01/2022, 11:33:13 PM     LOG [7398d3ad-c246-4650-8dd0-f8f29238bdd7] AppController.getHello -> nextTick -> setTimeout

API

AsyncContext almost identical to native Map object

class AsyncContext {
  // Clear all values from storage
  clear(): void;

  // Delete value by key from storage
  delete(key: K): boolean;

  // Iterate over storage
  forEach(callbackfn: (value: V, key: K, map: Map<K, V>) => void, thisArg?: any): void;

  // Get value from storage by key
  get(key: K): V | undefined;

  // Check if key exists in storage
  has(key: K): boolean;

  // Set value by key in storage
  set(key: K, value: V): this;

  // Get number of keys that stored in storage
  get size: number;

  // Register context, it's better to use this method inside the interceptor
  register(): void

  // Register context for a callback, it's better to use this inside the middleware
  registerCallback<R, TArgs extends any[]>(callback: (...args: TArgs) => R, ...args: TArgs): R

  // Unregister context
  unregister(): void
}

AsyncContextModule

interface AsyncContextModuleOptions {
  // Should register this module as global, default: true
  isGlobal?: boolean

  // In case if you need to provide custom value AsyncLocalStorage
  alsInstance?: AsyncLocalStorage<any>
}

class AsyncContextModule {
  static forRoot (options?: AsyncContextModuleOptions): DynamicModule
}

Migration guide from V1

You need to replace AsyncHooksModule by AsyncContextModule.forRoot()

License

MIT

async-context's People

Contributors

alreadyexisted avatar dependabot[bot] avatar techvlad avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

async-context's Issues

Can't run project (DEL)

I have "[Nest] 2170 - 10/03/2021, 3:12:22 PM [ExceptionHandler] Async ID (8052) is not registered within internal cache."
error message during nest initialization.
What can be a reason?

Can simultaneous request override traceId ?

If two users will send 2 requests simultaneously:

  • first one will set traceId: some-uuid-1,
  • second one will set traceId: some-uuid-2,

then:

  • first one will log some-uuid-2 (but it should log some-uuid-1, becuase this is first request)
  • second one will log proper traceId some-uuid-2

Am I right or Am I wrong?

Incomplete type for AsyncContext

Hello,

When I check de type file for AsyncContext, it looks like it:

export declare class AsyncContext implements OnModuleInit, OnModuleDestroy {
    private readonly internalStorage;
    private readonly asyncHookRef;
    private static instance;
    private constructor();
    static getInstance(): AsyncContext;
    onModuleInit(): void;
    onModuleDestroy(): void;
    set<TKey = any, TValue = any>(key: TKey, value: TValue): void;
    get<TKey = any, TReturnValue = any>(key: TKey): TReturnValue;
    register(): void;
    private getAsyncStorage;
    private static initialize;
}

It seems that we have some missing methods listed in the doc:

class AsyncContext {
  // Clear all values from storage
  clear(): void;

  // Delete value by key from storage
  delete(key: K): boolean;

  // Iterate over storage
  forEach(callbackfn: (value: V, key: K, map: Map<K, V>) => void, thisArg?: any): void;

  // Get value from storage by key
  get(key: K): V | undefined;

  // Check if key exists in storage
  has(key: K): boolean;

  // Set value by key in storage
  set(key: K, value: V): this;

  // Get number of keys that stored in storage
  get size: number;

  // Register context, it's better to use this method inside the interceptor
  register(): void

  // Register context for a callback, it's better to use this inside the middleware
  registerCallback<R, TArgs extends any[]>(callback: (...args: TArgs) => R, ...args: TArgs): R

  // Unregister context
  unregister(): void
}

Regards

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.