0

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!

Zoltan Hernyak
  • 989
  • 1
  • 14
  • 35

1 Answers1

0

To inject the request into a factory, you need to add inject: [REQUEST] to the custom provider object.

Side note, req.user will probably be undefined as it won't have been populated yet, so it would be better to make a getter object that can be referenced on demand to get the value later rather than pulling the value off immediately

Jay McDoniel
  • 57,339
  • 7
  • 135
  • 147
  • I read your similar suggestion here in stackoverflow on another question - I added the question there, now I must add also here: when I add `inject: [REQUEST],` - typescript compiler underlines the word `REQUEST` saying it is unknown. What is `REQUEST`? Where it came from? – Zoltan Hernyak Jul 22 '23 at 04:54
  • `@nestjs/core`, [like the docs show](https://docs.nestjs.com/fundamentals/injection-scopes#request-provider) – Jay McDoniel Jul 22 '23 at 05:39