简体   繁体   English

如何在自定义装饰器中使用 NestJS 反射器?

[英]How to use NestJS Reflector inside a Custom Decorator?

I am using a @SetMetaData('version', 'v2') to set versioning for a http method in a controller.我正在使用@SetMetaData('version', 'v2')为 controller 中的 http 方法设置版本控制。 Then I have a custom @Get() decorator to add the version as a postfix to the controller route.然后我有一个自定义的@Get()装饰器将版本作为后缀添加到 controller 路由。

So that, I would be able to use /api/cats/v2/firstfive , when I have这样,我就可以使用/api/cats/v2/firstfive ,当我有

@SetMetaData('version', 'v2')
@Get('firstfive')

But I don't see a clear way to inject Reflector to my custom @Get decorator.但我没有看到将 Reflector 注入我的自定义 @Get 装饰器的明确方法。

My Get decorator is as follows,我的 Get 装饰器如下,

import { Get as _Get } from '@nestjs/common';
export function Get(path?: string) {
  version = /*this.reflector.get('version') or something similar */
  return applyDecorators(_Get(version+path));
}

Please Help me out here!请帮帮我! Thanks!谢谢!

In decorators, you aren't able to get class properties, or do any sort of injection, so you wouldn't be able to get this.reflector or anything like that.在装饰器中,您无法获得 class 属性,或进行任何类型的注入,因此您将无法获得this.reflector或类似的东西。 What you could do is set up your own decorator that mimics @Get() and uses the Reflect.getOwnMetadata() methods, then returns the ``@Get()` decorator.可以做的是设置你自己的装饰器来模仿@Get()并使用Reflect.getOwnMetadata()方法,然后返回“@Get()”装饰器。 Might be a bit messy, but something along the lines of可能有点乱,但大致上

export function Get(path: string): MethodDecorator {
  return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {
    const version = Reflect.getMetadata('version', target, propertyKey);
    Reflect.defineMetadata(PATH_METADATA, version + path, descriptor.value);
    Reflect.defineMetadata(METHOD_METADATA, RequestMethod.GET, descriptor.value);
    return descriptor;
  }
}

Where PATH_METHOD and METHOD_METADATA are improted from @nestjs/common/constants and RequestMethod is imported from @nestjs/common/enums .其中PATH_METHODMETHOD_METADATA是从@nestjs/common/constants导入的, RequestMethod是从@nestjs/common/enums导入的。 This would create a new @Get() decorator for you that works in tandem with your @SetMetadata() method.这将为您创建一个新的@Get()装饰器,它与您的@SetMetadata()方法协同工作。 If I remember correctly decorators are ran bottom up, so make sure @SetVersion() comes before the @Get()如果我没记错装饰器是自下而上运行的,那么请确保@SetVersion()出现在@Get()之前

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

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