#@Controller value
22 messages · Page 1 of 1 (latest)
Hey! What would be the use case for this?
ChatGPT gave me this and it's working :
const controller = context.getClass();
const controllerPath = this.reflector.get<string>("path", controller);
Is this the Nest decorator @Controller()? It is possible, just gotta get the right metadata key
Yes it is, but I don't know where ChatGPT found the right key, that was my initial question
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'
Is it possible to access this information within a Nestjs CustomDecorator ? I'm creating a custom decorator and I need this data
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
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 ?
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 {}
I doesn't need to inject "Reflect" ?
No, strictly there's no need for that
Anytime! I highly recommend reading Typescript docs on decorators: https://www.typescriptlang.org/docs/handbook/decorators.html
TypeScript Decorators overview
Is there a difference between Typescript decorators and CustomDecorator made with Nestjs tools (like SetMetadata) ?
Essentially, no. One is just a wrapper around the other
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)
)