Nestjs 自定义装饰器
用命令自动生成装饰器文件,亦可手动创建
nest g d decorator
import { SetMetadata, createParamDecorator, ExecutionContext, applyDecorators } from '@nestjs/common';
import type { Request } from 'express'
export const Role = (...args: string[]) => SetMetadata('role', args);
export const ReqUrl = createParamDecorator((data: string, context: ExecutionContext) => {
const req = context.switchToHttp().getRequest<Request>()
console.log('data:', data);
return req.url
})
Decorator 使用方法
import { Controller, } from '@nestjs/common'
import { Role, ReqUrl } from './decorator'
@Controller()
export class DemoController {
@Get()
@Role('admin')
findAll(@ReqUrl('data') url: string) {
console.log('url:', url)
return this.guardService.findAll();
}
}