Kind: Function
Source: packages/common/decorators/core/apply-decorators.ts
Part of: Common
Function that returns a new decorator that applies all decorators provided by param
Useful to build new decorators (or a decorator factory) encapsulating multiple decorators related with the same feature
applyDecorators combines multiple class, method, or property decorators into a single reusable decorator. It applies each supplied decorator in order, making it useful for creating feature-specific decorator factories that encapsulate related metadata, guards, interceptors, or other decorator behavior.
Signature
tsfunction applyDecorators(decorators: Array<ClassDecorator | MethodDecorator | PropertyDecorator>)
Parameters
| Name | Type |
|---|---|
decorators | `Array<ClassDecorator |
Diagram
mermaidgraph LR A[Custom decorator factory] --> B[applyDecorators] B --> C[Decorator 1] B --> D[Decorator 2] B --> E[Decorator N] C --> F[Target class, method, or property] D --> F E --> F
Usage
tsimport {
applyDecorators,
SetMetadata,
UseGuards,
} from '@nestjs/common';
const RolesGuard = class {};
export function AdminOnly() {
return applyDecorators(
SetMetadata('roles', ['admin']),
UseGuards(RolesGuard),
);
}
class UsersController {
@AdminOnly()
removeUser() {
return 'User removed';
}
}
AI Coding Instructions
- Use
applyDecoratorswhen multiple decorators represent one cohesive feature or policy, such as authorization, caching, or API behavior. - Preserve decorator ordering, since decorators are applied in the order they are passed to
applyDecorators. - Ensure every provided decorator is valid for the intended target type: class, method, or property.
- Prefer creating named decorator factories, such as
AdminOnly()orPublicEndpoint(), instead of repeating the same decorator combination across controllers.
Was this page helpful?