Decorators
In NestJS, decorators are functions that can be applied to classes, methods, or properties to modify their behavior. They provide a declarative approach to adding functionality to your code, making it more concise and readable. here are some examples:
@Module(): Defines a module.@Controller(): Defines a controller class that handles HTTP requests.@Get(): Maps an HTTP GET request to a method.@Post(): Maps an HTTP POST request to a method.@Param(): Extracts route parameters.@Body(): Extracts data from the request body.@Query(): Extracts query parameters.
Decorators in NestJS are implemented as functions that are executed at runtime and can manipulate metadata for the class, method, or parameter they are applied to.
Custom decorators
Custom decorators are a way to define reusable, declarative annotations that can be used on classes, methods, or parameters in your application. They are used to attach metadata to specific elements of your application and can simplify complex logic by abstracting it behind simple, reusable annotations.
Custom decorators help reduce boilerplate code, enhance readability, and improve maintainability.
example
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
export const User = createParamDecorator( (data: unknown, ctx: ExecutionContext) => { const request = ctx.switchToHttp().getRequest(); return request.user; // Assume 'user' is in the request object },);The @User() decorator will automatically extract the user from the request object and pass it to the method.