Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
142
rated 0 times [  147] [ 5]  / answers: 1 / hits: 9646  / 3 Years ago, tue, january 5, 2021, 12:00:00

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!


More From » node.js

 Answers
16

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()


[#2014] Tuesday, December 29, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ariel

Total Points: 523
Total Questions: 111
Total Answers: 100

Location: Anguilla
Member since Sun, Jan 29, 2023
1 Year ago
;