Diving Deep into NestJS Decorators

Deepika Juneja

--

In NestJS, using decorators is a great way to enhance code readability and structure. Decorators in NestJS are built on top of TypeScript decorators, and provide a declarative way to add metadata as well as annotations to classes and their members.

Quoting the TypeScript Documentation,

A Decorator is a special kind of declaration that can be attached to a class declaration, method, accessor, property, or parameter. Decorators use the form @expression, where expression must evaluate to a function that will be called at runtime with information about the decorated declaration.

In my previous blogs on API Request Validation in NestJS and Custom Validators in NestJS, I’ve already talked about Decorators and Custom Decorators, and how can they enhance the security and readability of our application. You can explore them here:

In this blog, I’ll be sharing some important points to consider while working with NestJS decorators:

Applying Multiple Decorators

NestJS allows the application of multiple decorators on a declaration.

There are 2 ways to achieve this:

  • Single-line declaration:
@f @g x
  • Multi-line declaration:
@f 
@g
x

Order of Evaluation

TypeScript decorators are executed bottom-to-top. The same holds true for NestJS decorators too.

Following is an excerpt from Typescript Documentation to explain this further:

When multiple decorators apply to a single declaration, their evaluation is similar to function composition in mathematics. In this model, when composing functions f and g, the resulting composite (fg)(x) is equivalent to f(g(x)).

As such, the following steps are performed when evaluating multiple decorators on a single declaration in TypeScript:

1. The expressions for each decorator are evaluated top-to-bottom.

2. The results are then called as functions from bottom-to-top.

Decorator Composition

NestJS enables the developers to club multiple decorators into a single custom decorator using applyDecorators. This practice comes in handy when you want to re-use multiple decorators related to a specific feature of your application.

Here’s an example:

import { applyDecorators } from ‘@nestjs/common’; 

export function Auth(…roles) {
return applyDecorators(
SetMetadata(‘roles’, roles),
UseGuards(AuthGuard, RolesGuard),
ApiBearerAuth(),
ApiUnauthorizedResponse({ description: ‘Unauthorized’ }),
);
}

Decorator Composition promotes modularity and reusability, and makes the code a lot more readable.

That’s it for this blog. Feel free to check out my other blogs to further expand your knowledge on NestJS!

--

--

No responses yet

Write a response