Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is metadata in nestjs framework and when to use method @setmetadata?

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?

like image 640
Jakapong Chan-o Avatar asked Oct 28 '25 14:10

Jakapong Chan-o


2 Answers

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.

enter image description 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.

like image 62
Ahmed Avatar answered Oct 31 '25 12:10

Ahmed


https://docs.nestjs.com/fundamentals/execution-context#reflection-and-metadata:

The @SetMetadata() decorator is imported from the @nestjs/common package.

like image 37
Micael Levi Avatar answered Oct 31 '25 10:10

Micael Levi