How to inject service inside a module function NestJS

99 Views Asked by At

I'm using pino-logger in my NestJS project to log the activities in my application, and I'm logging the object along with ReqId so I can trace the whole activity inside one request. I'd like to use the same "ReqId" in another place as well, but I'm unsure of how to move it outside of the module, so for that, I'm thinking to save that generated ReqId into the CacheManager but not sure how to inject CacheManager class inside genReqId function. Please look over the code below.

app.module.ts

@Module({
  imports: [
    LoggerModule.forRoot({
      pinoHttp: {
        genReqId: (req: any) => {
          // I'm thinking to use CacheManager here but I'm not sure how to inject CacheManager class here
          return req.headers.req_id || uuid(); // from here it generate the request ID and I want to export this ID and use in side an another class
        },
        base: undefined,
        quietReqLogger: true,
        timestamp: false,
      },
    }),
  ],
})
export class AppModule {}
1

There are 1 best solutions below

1
Abdul Saiyad On

you need To create sharable service and import it Imports

@Injectable()
export class RequestIdService {
  private reqId: string;

  setRequestId(reqId: string) {
    this.reqId = reqId;
  }

  getRequestId() {
    return this.reqId;
  }
}

than import it to logger module

  imports: [
    LoggerModule.forRoot({
      pinoHttp: {
        genReqId: (req: any) => {
          this.requestIdService.setRequestId(req.headers.req_id || uuid());
          return this.requestIdService.getRequestId();
        },
        base: undefined,
        quietReqLogger: true,
        timestamp: false,
      },
    }),
  ],
  providers: [RequestIdService],
    ```

use that service by

import { RequestIdService } from './request-id.service'; this.requestIdService.getRequestId()