Explain what the Decorator pattern is and how it is used in the NestJS framework.
sobes.tech AI
Answer from AI
The Decorator pattern is a structural design pattern that allows dynamically adding new responsibilities to objects by wrapping them in 'decorators'. It is an alternative to inheritance, enabling functionality extension without modifying the original code.
In NestJS, decorators are widely used to annotate classes, methods, parameters, and properties to add metadata, which is then processed by the framework. For example, decorators like @Controller(), @Get(), @Injectable() are special functions that modify the behavior of classes or methods.
An example of a simple custom decorator in NestJS:
import { SetMetadata } from '@nestjs/common';
export const Roles = (...roles: string[]) => SetMetadata('roles', roles);
// Usage:
@Controller('users')
export class UsersController {
@Get()
@Roles('admin')
findAll() {
// method is accessible only for admin roles
}
}
Thus, the Decorator pattern in NestJS helps add metadata and extend the functionality of classes and methods without changing their internal logic.