Nestjs大量用到装饰器decorator,所以Nestjs也允许用户自定义装饰器
创建自定义装饰器:
实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| import { SetMetadata } from '@nestjs/common';
export const Role = (...args: string[]) => SetMetadata('role', args);
export const ReqUrl = createParamDecorator( (data: string, ctx: ExecutionContext) => { const req = ctx.switchToHttp().getRequest<Request>(); console.log(data, 'data'); return req.url; }, );
|
在Controller中使用:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| import { Controller, Get, UseGuards, } from '@nestjs/common'; import { GuardService } from './guard.service'; import { RoleGuard } from './role/role.guard'; import { Role } from './role/role.decorator';
@Controller('guard')
@UseGuards(RoleGuard) export class GuardController { constructor(private readonly guardService: GuardService) {}
@Get() @Role('admin') @ReqUrl('I am data') url: string findAll() { console.log(url, 'url'); return this.guardService.findAll(); } }
|