Nest JS: Using Node AsyncLocalStorage inside Nest Pipes

Viewed 24

I am planning to use the NestJS Pipe for storing some app specific information through AsyncLocalStorage of Node JS. (Node version is 18.x).

I am planning to mimic the Nest JS Request Context to store app-specific request context.

For that I need to adhere to the AsyncStorage Run method.

Something like this:


import {ArgumentMetadata, Injectable, PipeTransform} from '@nestjs/common';
import { Request, Response } from 'express';
import { MyRequestContext } from './my-request-context.model';

@Injectable()
export class RequestContextPipe implements PipeTransform {
    constructor() {}  // any services can be injected here

    async transform(publicId: string, metadata: ArgumentMetadata) {
        // Here we will have logic which will get the various values we want to set in the RequestContext. Lets call that as appContext.
        // MyRequestContext.cls.run(new MyRequestContext(req, res, appContext), next);

    }
}
import { AsyncLocalStorage } from 'async_hooks';
import { Request, Response } from 'express';

export class MyRequestContext {
  static cls = new AsyncLocalStorage<RequestContext>();

  static get currentContext() {
    return this.cls.getStore();
  }

  constructor(public readonly req: Request, public readonly res: Response, public readonly appContext: AppData) {}
}

But the problem I am facing:

How to get the request, response and next inside a Nest JS pipe?

I want to execute this line of code inside NestJS Pipe's transform method:

     MyRequestContext.cls.run(new MyRequestContext(req, res, appContext), next);

So I need the request, response and next inside the Pipe.

How may I get it?

0 Answers
Related