在 Nestjs 中我们使用了大量装饰器 decorator ,所以 Nestjs 也允许我们去自定义装饰器。
案例一 自定义权限装饰器
生成装饰器 nest g d [name]
import { SetMetadata } from '@nestjs/common';
export const Role = (role: string[]) => {
console.log(role,1)
return SetMetadata('role', role);
}
// 使用
@Role(['admin'])
create(@Body() createUserDto: CreateUserDto) {
return this.userService.create(createUserDto)
}
案例二 自定义参数装饰器返回一个 url
import { SetMetadata,createParamDecorator,ExecutionContext ,applyDecorators } from '@nestjs/common';
import type {Request} from 'express'
export const ReqUrl = createParamDecorator((data:string,ctx:ExecutionContext)=>{
const req = ctx.switchToHttp().getRequest<Request>()
return req.url
})
// 使用
@Get()
findAll(@ReqUrl() url) {
return this.userService.findAll()
}
聚合装饰器
applyDecorators 可以把多个装饰器组合起来
applyDecorators(Role, Requrl)
