#@Controller value

22 messages · Page 1 of 1 (latest)

thick crest
#

I have a controller class with the @Controller decorator and a value, let's say "test" (@Controller("test)) and I would like to have the metadata key with which I could access the @Controller value (here "test") from my Interceptor and using Reflector, is it possible ?

iron mauve
#

Hey! What would be the use case for this?

thick crest
#

ChatGPT gave me this and it's working :


                const controller = context.getClass();

                const controllerPath = this.reflector.get<string>("path", controller);

proud crypt
#

Is this the Nest decorator @Controller()? It is possible, just gotta get the right metadata key

thick crest
#

Yes it is, but I don't know where ChatGPT found the right key, that was my initial question

proud crypt
#

It is the correct key. You'd need to look into Nest's source codee. There's a PATH_METADATA variable under @nestjs/common/constants that is the string 'path'

thick crest
#

Is it possible to access this information within a Nestjs CustomDecorator ? I'm creating a custom decorator and I need this data

iron mauve
#

I really believe that if you share with us the goal you are trying to accomplish we'll be in a better position to help

thick crest
#

export const CustomTopic = () => SetMetadata(CustomTopic .name, **@Controller("test")**); 

#

I want to replace "@Controller("test")" by the value of the metadata key "path", which is in this example "test", is it possible here ?

iron mauve
#

To be clear, you want the following:

@CustomTopic() // you want this decorator to access value "test"?
@Controller("test")
class MyController {}
#

If that's the case you can write the decorator in the following way:

function CustomTopic() {
  return function (controller) {
    const value = Reflect.getMetadata(PATH_METADATA, controller);
    // value = 'test', do what's needed
  };
}

@CustomTopic()
@Controller('test')
class MyController {}
thick crest
#

I doesn't need to inject "Reflect" ?

iron mauve
#

No, strictly there's no need for that

thick crest
#

Ooh I didn't knew about Reflect. I only knew about Reflector haha

#

Thank you !

iron mauve
thick crest
#

Is there a difference between Typescript decorators and CustomDecorator made with Nestjs tools (like SetMetadata) ?

proud crypt
#

What is the end goal here? You may be able to make your own decorator that wraps the @Controller() so you can do whatever you want with the path without needing to involve getting the metadata using the Reflect class at all

#

Something like

export const CustomTopic = (path: string) => applyDecorators(
  SetMetadata('CustomTopic', path),
  Controller(path)
)