简体   繁体   English

Nest.js 在请求中使用自定义值 object

[英]Nest.js use custom value in the request object

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.我想在请求 object 上保留公司的价值,以便稍后在我的 controller 上使用它。 How to do that in Nest.js?如何在 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?我应该使用session还是有更简单的方法可以做到这一点?

You can just add the company to a custom field on the request.您可以将company添加到请求的自定义字段中。 request.company = company and then in the controller you can use @Req() to get the request object and .company to get the company value. request.company = company然后在 controller 中,您可以使用@Req()获取请求 object 和.company以获取公司价值。 Or you could create a custom decorator to get the company for you.或者您可以创建一个自定义装饰器来为您获取公司。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM