Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 369
Nikhil.Nixel Avatar asked Oct 20 '25 13:10

Nikhil.Nixel


1 Answers

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

like image 115
Jay McDoniel Avatar answered Oct 22 '25 01:10

Jay McDoniel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!