Add request injection token#

Set reference to request object#

application.use((req, res, next) => {
  // Create context ...

  // attach the request to the context so you can refernce it later on
  context.setExtra("request", req);

  // rest of code
});

Create InjectionToken#

request_token.ts file

import { Request } from "express";
export const REQUEST_TOKEN = new InjectionToken<Request>("TOKEN_REQUEST", {
  lifetime: ServiceLifetime.Scoped,
  implementationFactory: (context) => context.getExtra("request"),
});

Use @Inject to reference REQUEST_TOKEN#

@Injectable({
  lifetime: ServiceLifetime.Scoped,
})
export class DataService {
  constructor(@Inject(REQUEST_TOKEN) private request: Request) {
    const userAgent = request.headers["user-agent"];
  }
}

Make sure that the service that utilize the REQUEST_TOKEN is

  1. Either Transient or Scoped.
  2. Descendant of Scoped controller