Performance: Reflector and custom decorators
This affects server-side request handling speed and memory usage by controlling metadata access and decorator execution.
import { SetMetadata, Reflector } from '@nestjs/core'; const Roles = (...roles: string[]) => SetMetadata('roles', roles); @Roles('admin') @Get('admin') getAdminData() { // handler code } // Use Reflector in guards or interceptors to access metadata once per request
import { ReflectMetadata } from '@nestjs/common'; @ReflectMetadata('roles', ['admin']) @Get('admin') getAdminData() { // handler code } // Access metadata manually in every request handler
| Pattern | Metadata Lookups | CPU Blocking | Request Latency | Verdict |
|---|---|---|---|---|
| Manual ReflectMetadata in each handler | Multiple per request | Minimal but repeated | Higher latency | [X] Bad |
| SetMetadata with Reflector in guards | Single per request | None | Lower latency | [OK] Good |
| Synchronous logic in decorators | N/A | Blocks event loop | Increased latency | [X] Bad |
| Asynchronous interceptors for logic | N/A | Non-blocking | Minimal latency | [OK] Good |
Reflector class in NestJS when used with custom decorators?getData method?import { Controller, Get, UseGuards, SetMetadata } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
const Roles = (roles: string[]) => SetMetadata('roles', roles);
@Controller('items')
export class ItemsController {
@Get()
@Roles(['admin'])
getData() {
return 'secret data';
}
}
// In a guard:
const reflector = new Reflector();
const roles = reflector.get<string[]>('roles', ItemsController.prototype.getData);
console.log(roles);import { SetMetadata } from '@nestjs/common';
function Permissions(permissions: string[]) {
return (target: any, key: string) => {
Reflect.defineMetadata('permissions', permissions, target, key);
};
}
class UserController {
@Permissions(['read'])
getUser() {
return 'user';
}
}@Roles decorator metadata. Which approach correctly uses Reflector and the custom decorator to achieve this?Pass the test and this pattern moves unknown