I create a guard that are like these
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { AuthService } from './auth.service';
@Injectable()
export class CompanyGuard implements CanActivate {
constructor(private readonly authService: AuthService) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest();
const token = request.headers['token'];
if (token) {
const company = await this.authService.validateToken(token);
return company ? true : false;
} else {
return false;
}
}
}
I want to keep the value of company on the request object, so I can use it later on my controller. How to do that in Nest.js? I tried to look it on the docs, but I'm confused. Should I use the session or there are more simple way to do that?
You can just add the company
to a custom field on the request. request.company = company
and then in the controller you can use @Req()
to get the request object and .company
to get the company value. Or you could create a custom decorator to get the company for you.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.