Boyang Li
Boyang Li

Reputation: 93

Is there a way to get request context within a decorator in Nest JS

I am trying to build a decorator to "log" request info

export const Tracking = () => {
  return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {
    const method = descriptor.value;
    descriptor.value = async function(...args: any[]) {
      console.log(/** Request info */)
      console.log(/** Headers, Body, Method, URL...*/)
      return method.call(this, ...args);
    }
  }
}

and try to use it on a controller method like this.

export class Controller {

  @Get('/path')
  @Tracking()
  public async getData(@Headers('user') user: User) {
    return this.service.getData(user.id);
  }
}

If this is impossible, is there a way to apply interceptor to some method of controller?
Or is there a thread(like)-level context for request?

Thanks!!

Upvotes: 2

Views: 6190

Answers (1)

Jay McDoniel
Jay McDoniel

Reputation: 70151

Decorators don't have access to the request information because of what a decorator is. It's a higher order function that is called to set metadata for the class, class member, class method, or class method parameter. This metadata can be read at runtime, but it is called and set essentially as soon the file is imported. Due to this, there's no way to call a decorator on each request, even Nest's @Body() and @Req() are called at the time of import and read at the time of the request (actually earlier but that's besides the point).

What you're looking for here sounds more like an interceptor, like Micael Levi and hoangdv have already mentioned. The Nest docs show a basic logging example, and there are packages out there like @ogma/nestjs-module (disclaimer: I'm the author) that handle this request logging/tracking for you including the addition of correlation IDs.

Upvotes: 6

Related Questions