I have this controller
@Post('/login')
async login(@Res() res: Response, @Body() body: LoginDto) {
try {
const user = await this.authService.login(body);
return ResponseUtil.success(res, user, 'nice');
} catch (error) {
return ResponseUtil.serverError(res, error.stack);
}
}
I want to use res
in authService
without passing down res
like this:
const user = await this.authService.login(res, body);
Or how can I use res
in global?
2
Answers
You can use dependency injection and global interceptor/middlewar to use response object from NestJS in your service without passing it down through method parameters
Create a file
response.decorator.ts
Create a
auth.controller.ts
Create a
auth.service.ts
To access
res
inauthService
without passing it explicitly, we can make a combination of a custom provider and middleware in NestJS.Create a Response Provider
Create Middleware to Inject Response
Apply Middleware in Module
Access Response in AuthService
Controller