In nestJS it is said that we can read properties from the request and insert into DI like this:
@Module({
controllers: [UserController],
providers: [
{
provide: 'USER',
scope: Scope.REQUEST,
useFactory: (req:Request) => req["user"] ?? null,
},
],
exports: ['USER'],
})
Supposing a middleware reads the Bearer token, decode it and adds it to the current request as req.user = <userINstance>
later I want to read it from it and adds to DI with token 'USER'.
In UserController I want to receive it as the following:
@Controller('/users')
export default class UserController {
@Inject('USER') protected user: IUser;
...
}
But the factory wont work: it says
ERROR [ExceptionsHandler] Cannot read properties of undefined (reading 'user')
It seems the req
is null, so req["user"]
drops this exception. Tried to implement a similar simple example where tried to inject the req.method
(post/get/etc) as string into DI. Same happened.
How to implement a factory like this? How to tell the nestJS that req
is the current request? For example the following drops syntax error:
useFactory: (@Req() req:Request) => req["user"] ?? null,
Thanks in advance!