javascript - 在 nest.js 中,是否可以在参数装饰器中获取服务实例?

标签 javascript node.js typescript decorator nestjs

我想使用 nest.js 实现这样的目标: (与 Spring 框架非常相似的东西)

@Controller('/test')
class TestController {
  @Get()
  get(@Principal() principal: Principal) {

  }
}

经过几个小时的阅读文档,我发现 nest.js 支持创建自定义装饰器。所以我决定实现我自己的 @Principal 装饰器。装饰器负责从 http header 中检索访问 token ,并使用该 token 从我自己的身份验证服务中获取用户主体。

import { createParamDecorator } from '@nestjs/common';

export const Principal = createParamDecorator((data: string, req) => {
  const bearerToken = req.header.Authorization;
  // parse.. and call my authService..
  // how to call my authService here?
  return null;
});

但问题是我不知道如何在装饰器处理程序中获取我的服务实例。是否可以?如何?提前谢谢你

最佳答案

无法将服务注入(inject)您的自定义装饰器。

相反,您可以创建一个可以访问您的服务的 AuthGuard。然后守卫可以向 request 对象添加一个属性,然后您可以使用自定义装饰器访问该对象:

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private authService: AuthService) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const request = context.switchToHttp().getRequest();
    const bearerToken = request.header.Authorization;
    const user = await this.authService.authenticate(bearerToken);
    request.principal = user;
    // If you want to allow the request even if auth fails, always return true
    return !!user;
  }
}
import { createParamDecorator } from '@nestjs/common';

export const Principal = createParamDecorator((data: string, req) => {
  return req.principal;
});

然后在你的 Controller 中:

@Get()
@UseGuards(AuthGuard)
get(@Principal() principal: Principal) {
  // ...
}

请注意,nest 提供了一些用于身份验证的标准模块,请参阅 docs .

关于javascript - 在 nest.js 中,是否可以在参数装饰器中获取服务实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55560858/

相关文章:

javascript - 创建日期验证器

javascript - 我收到错误 : failed to connect to [undefined:27017]

javascript - 如何使用 Angular 动态更改css类

javascript - 用于检查权限的包装器

javascript - 用javascript获取字符串的路径?

javascript - 如何在 html/javascript 中访问单个图像上的单独点/部分?

node.js - Golang 中的 package.json 等价物

node.js - 如何在 node.js 中创建命名管道?

javascript - 使用 typescript 使用模板创建 HTML

javascript - 从 Typescript 中同一类的另一个方法调用方法