1.3.0 • Published 4 years ago

@quicksend/nestjs-request-context v1.3.0

Weekly downloads
-
License
MIT
Repository
github
Last release
4 years ago

NestJS Request Context

Keep track of request-level data in NestJS using AsyncLocalStorage

Prerequisites

Installation

$ npm install @quicksend/nestjs-request-context

Usage

RequestContext

First, create a class that extends RequestContext. This class will hold your request-level data.

import { RequestContext as BaseRequestContext } from "@quicksend/nestjs-request-context";

export class RequestContext extends BaseRequestContext<RequestContext>() {
  data?: string;
}

RequestContextMiddleware

Next, apply RequestContextMiddleware as a global middleware and pass in our request context as a parameter:

import { MiddlewareConsumer, Module, NestModule, RequestMethod } from "@nestjs/common";

import { RequestContextMiddleware } from "@quicksend/nestjs-request-context";

import { RequestContext } from "./request.context";

@Module()
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer): void {
    consumer.apply(RequestContextMiddleware(RequestContext)).forRoutes({
      method: RequestMethod.ALL,
      path: "*"
    });
  }
}

You can now access the request context from anywhere in your application.

import { Controller, Get } from "@nestjs/common";

import { RequestContext } from "./request.context";

@Controller()
export class AppController {
  @Get()
  get(): RequestContext {
    const store = RequestContext.getStore();

    store.data = "test";

    const data = RequestContext.getItem("data");
    
    console.log(item); // "test"

    return store;
  }
}

RequestContextInterceptor

For use cases where a middleware is not appropriate (i.e. NestJS microservices), you can use the RequestContextInterceptor. It can be applied normally like any other interceptor. Note that interceptors run after guards, refer to the request lifecycle here.

import { Controller, Post, Query, UseInterceptors } from "@nestjs/common";

import { RequestContextInterceptor } from "@quicksend/nestjs-request-context";

import { RequestContext } from "./request.context";

@Controller()
export class AppController {
  @Get()
  @UseInterceptors(RequestContextInterceptor(RequestContext))
  get(): RequestContext | undefined {
    const store = RequestContext.getStore();

    store.data = "test";

    const data = RequestContext.getItem("data");
    
    console.log(item); // "test"

    return store;
  }
}

Tests

Run tests using the following commands:

$ npm run test
$ npm run test:watch
1.3.0

4 years ago

1.2.0

4 years ago

1.1.1

4 years ago

1.1.0

4 years ago

1.0.1

4 years ago

1.0.0

4 years ago