From the course: Mastering Nest.js: Build Scalable Applications with Mastery in Nest.js Framework

Unlock this course with a free trial

Join today to access over 25,200 courses taught by industry experts.

Setting custom metadata: A better way

Setting custom metadata: A better way

Previously, we saw how to attach metadata to a route handler, where we used the set metadata decorator. But this way of directly providing metadata to a route handler is not considered a good practice. So, there is an alternate and a better way to provide or attach custom metadata to any route handler. Let's see how we can do that. So first of all, to attach a role value with metadata, instead of specifying a role value directly, a better approach is to create an enum of roles. I'll create a folder, naming it as enum and a TypeScript file, roles.enum.ts, in which I'll create an enum called role and the values user equals user and admin equals admin. We will use these enum values for assigning roles. Now I'm going to create a custom decorator for assigning the metadata. I'm again creating a folder, naming it as custom decorator and a TypeScript file roles.decorator.ts. Here we will import the set metadata decorator from the nestjs common module. Then I'll export a constant named roles,…

Contents