I am learning a course topic reflection and metadata from nest documentation. They used @setmetadata('roles') but I don't know metadata come from and when they are used?
I don't know metadata come from
First lets explain what metadata generally means. Metadata in general means data about data. Its a description of the data in more simpler terms (for e.g data about an image). Taking an example from here.

They used
@setmetadata('roles').
Nest provides the ability to attach custom data to route handlers through @SetMetadata. Its a way to declaratively define and store data about your controller(endpoint).
@SetMetadata stores the key value pairs. For example,
SetMetadata('IS_PUBLIC_KEY', true)
findAll(@Query() paginationQuery: PaginationQueryDto) {
return this.testService.findAll(paginationQuery);
}
Here I am setting a key IS_PUBLIC_KEY with a value set to true.
In this scenario you are defining a key named role (most probably and it seems it may be missing a value) which will define what certain types or role can access this controller.
When they are used?
You can use it when you want to define the Guards. For instance, I am using the above findAll controller as a public api. In my guard implementation, I check and see if the value of IsPublic is true then allow any consumer to consume the API.
canActivate(
context: ExecutionContext,
): boolean | Promise<boolean> | Observable<boolean> {
const isPublic = this.reflector.get('IS_PUBLIC_KEY', context.getHandler());
if (isPublic) {
return true;
}
}
Hope this answers your question.
https://docs.nestjs.com/fundamentals/execution-context#reflection-and-metadata:
The
@SetMetadata()decorator is imported from the@nestjs/commonpackage.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With