Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
617 views
in Technique[技术] by (71.8m points)

javascript - 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. Then I have a custom @Get() decorator to add the version as a postfix to the controller route.

So that, I would be able to use /api/cats/v2/firstfive, when I have

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

But I don't see a clear way to inject Reflector to my custom @Get decorator.

My Get decorator is as follows,

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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. What you could do is set up your own decorator that mimics @Get() and uses the Reflect.getOwnMetadata() methods, then returns the ``@Get()` decorator. 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. This would create a new @Get() decorator for you that works in tandem with your @SetMetadata() method. If I remember correctly decorators are ran bottom up, so make sure @SetVersion() comes before the @Get()


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...