I am using the NestJS middleware to inject some information in my response as locals for my controller. This happens like the following:
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
@Injectable()
export class AuthMiddleware implements NestMiddleware {
constructor(private userService: UserService) {}
async use(req: Request, res: Response, next: NextFunction) {
// do some stuff
res.locals.foo = "bar";
next();
}
}
In my controller I am doing the following:
import { Controller, Get, UseGuards, Response } from '@nestjs/common';
import { UserService } from '@/user/user.service';
import { AuthGuard } from '@nestjs/passport';
import { Response as r } from 'express';
@Controller()
export class AppController {
@Get('/')
@UseGuards(AuthGuard('jwt'))
helloWorld(@Response() res: r) {
res.status(200).send({ hello: r.locals.foo });
}
}
The problem I have is that I want to return actually a Promise instead of letting .send(...) to handle this. The reason why is I am using the OpenAPI NestJS generator mentioned here.
Notice that I am using Response from express (as r) to access locals. The challenge here is that if I don't use r but I would use the nestjs/common Response I am not able to access locals since it's not a variable.
Anyone solution around this? I read about decorators, I am wondering whether that's the only solution.
I am 100% sure that the middleware fires off as well since I am getting "bar" as expected from the middleware.
Thanks!