npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@alexy4744/nestjs-request-context

v1.1.0

Published

Keep track of request-level data in NestJS using AsyncLocalStorage

Downloads

10

Readme

NestJS Request Context

Keep track of request-level data in NestJS using AsyncLocalStorage

Prerequisites

Installation

$ npm install @alexy4744/nestjs-request-context

Usage

RequestContext

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

import { BaseRequestContext } from "@alexy4744/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 "@alexy4744/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 by importing it 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;
  }
}

For use cases where a middleware is not appropriate (i.e. NestJS microservices), you can use the RequestContextGuard or RequestContextInterceptor. Refer to the request lifecycle here to decide which one is the better option.

RequestContextGuard

The RequestContextGuard is ran after all middlewares, but before interceptors. This is the next best option for use cases where a middleware is not possible. RequestContextGuard uses the .enterWith() method to transition into the request context, making it a less-safer method. It is best to apply this guard before any other guards to minimize the risk of re-using the same context. The guard can be applied as any other global Nest guard.

import { APP_GUARD, Module, Post } from "@nestjs/common";

import { RequestContextGuard } from "@alexy4744/nestjs-request-context";

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

@Module({
  ...
  providers: [
    {
      provide: APP_GUARD,
      useClass: RequestContextGuard(RequestContext),
    },
    ...
  ]
})
export class AppModule {}

RequestContextInterceptor

Interceptors always run after all middleware and guards. This may not be useful because the request context will be unaccessible in middleware and guards as it is too late in the request lifecycle. However, RequestContextInterceptor uses the .run() method to transition into the context, making it a safer option rather than using RequestContextGuard. The RequestContextInterceptor can be applied as any other Nest interceptor.

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

import { RequestContextInterceptor } from "@alexy4744/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;
  }
}

Development

# Run e2e test
$ nx e2e nestjs-request-context-e2e
# Update version
$ nx version nestjs-request-context
# Build the project
$ nx build nestjs-request-context
# Publish new version on GitHub
$ git push --follow-tags origin master
# Publish new version on NPM
$ npm publish ./dist/packages/nestjs-request-context --access=public