Nestjs大量用到装饰器decorator,所以Nestjs也允许用户自定义装饰器

创建自定义装饰器:

1
nest g d [name]

实现:

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);

// data:外面传来的参数 ctx:上下文
export const ReqUrl = createParamDecorator(
(data: string, ctx: ExecutionContext) => {
const req = ctx.switchToHttp().getRequest<Request>();
console.log(data, 'data');
return req.url;
// 这个函数可以组合多个装饰器
// return applyDecorators(Role, xxx, xxxx)
},
);

在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();
}
}