简体   繁体   English

为什么我不能在构造函数中使用我的 nestjs 自定义装饰器?

[英]Why can't I use my nestjs custom decorator in a constructor?

I want to create a custom decorator to return tenant information.我想创建一个自定义装饰器来返回租户信息。 I have the following code:我有以下代码:

export type TenantInfo = {
    token: string
    id: string
}

export const TenantInfo = createParamDecorator(
  (data: unknown, context: ExecutionContext): TenantInfo => {
      // todo use context to get from auth header
      return { id: '1', token: 'todo' }
  },
);

Now i register it in the tenant service:现在我在租户服务中注册它:

@Injectable({ scope: Scope.REQUEST })
export class TenantService {
  private readonly _tenantInfo: TenantInfo;

  constructor(
    @TenantId() tenantInfo: TenantInfo,
  ) {
    this._tenantInfo = tenantInfo;
    logger.log(`Received GRPC message from tenant id ${tenantInfo.id}`);
  }
}

And when I run my code it says:当我运行我的代码时,它说:

Error: Nest can't resolve dependencies of the TenantService (?).错误:Nest 无法解析 TenantService (?) 的依赖关系。 Please make sure that the argument Object at index [0] is available in the TenantModule context.请确保索引 [0] 处的参数 Object 在 TenantModule 上下文中可用。

Potential solutions:潜在的解决方案:

  • If Object is a provider, is it part of the current TenantModule?如果 Object 是提供者,它是当前 TenantModule 的一部分吗?
  • If Object is exported from a separate @Module, is that module imported within TenantModule?如果 Object 是从单独的 @Module 导出的,那么该模块是否会导入到 TenantModule 中? @Module({ imports: [ /* the Module containing Object */ ] @Module({ imports: [ /* 包含对象的模块 */ ]

I'm not sure how to get around this.我不知道如何解决这个问题。 It's saying register it in the module but I get errors if I try putting TenantInfo in the providers array...意思是在模块中注册它,但是如果我尝试将 TenantInfo 放入 providers 数组中,我会收到错误...

Type '(...dataOrPipes: unknown[]) => ParameterDecorator' is not assignable to type 'Provider'类型 '(...dataOrPipes: unknown[]) => ParameterDecorator' 不可分配给类型 'Provider'

How do you do this?你怎么做到这一点? All I want is to get some details from the request context.我想要的只是从请求上下文中获取一些详细信息。

createParamDecorator only creates decorators that work for route handlers (Controllers, Resolvers, or Gateways). createParamDecorator仅创建适用于路由处理程序(控制器、解析器或网关)的装饰器。 For something that can be injected at the constructor level of a service you can either inject the request, via @Inject(REQUEST) , or you can create a custom request scoped provider and custom decorator like so:对于可以在服务的构造函数级别注入的东西,您可以通过@Inject(REQUEST)注入请求,或者您可以创建自定义请求范围提供程序和自定义装饰器,如下所示:

export const InjectTenantId = () => Inject('TENANTID');

export const tenantIdProvider = {
  provide: 'TENANTID',
  inject: [REQUEST],
  scope: Scope.REQUEST,
  useFactory: (request) => getTenantIdFromRequest(request)
}

And now in your constructor you can do @InjectTenantId() private readonly tenantInfo: TenantInfo .现在在您的构造函数中,您可以执行@InjectTenantId() private readonly tenantInfo: TenantInfo

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

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