0
0
NestJSframework~5 mins

Decorator-based architecture in NestJS

Choose your learning style9 modes available
Introduction

Decorators help organize code by adding special marks to classes and methods. This makes your app easier to read and manage.

When you want to mark a class as a controller to handle web requests.
When you need to define a method as a route handler for GET or POST requests.
When you want to inject services or dependencies into a class automatically.
When you want to add metadata to classes or methods for configuration.
When you want to create reusable code patterns that modify behavior cleanly.
Syntax
NestJS
@DecoratorName(parameters)
class MyClass {
  @DecoratorName(parameters)
  myMethod() {}
}
Decorators start with the @ symbol and are placed just above classes or methods.
They can take parameters to customize their behavior.
Examples
This marks the class as a controller handling routes under '/cats'.
NestJS
@Controller('cats')
class CatsController {}
This marks the method to handle GET requests to the controller's base route.
NestJS
@Get()
getAllCats() {
  return [];
}
This marks the class as a service that can be injected into other classes.
NestJS
@Injectable()
class CatsService {}
Sample Program

This example shows a service that provides cat names and a controller that handles GET requests to '/cats'. The decorators mark the roles clearly.

NestJS
import { Controller, Get, Injectable } from '@nestjs/common';

@Injectable()
class CatsService {
  getCats() {
    return ['Tom', 'Jerry'];
  }
}

@Controller('cats')
class CatsController {
  constructor(private readonly catsService: CatsService) {}

  @Get()
  findAll() {
    return this.catsService.getCats();
  }
}
OutputSuccess
Important Notes

Decorators help NestJS know what each class or method does without extra code.

Always import decorators from '@nestjs/common' to use them correctly.

Using decorators keeps your code clean and easy to understand.

Summary

Decorators add special meaning to classes and methods.

They help organize code by marking roles like controllers and services.

Using decorators makes your NestJS app easier to build and maintain.