跳到主要内容

自定义装饰器

自定义角色装饰器

我们在user里创建decorator

cd src/user
nest g d myrole

image-20221126102521678

创建成功的demo帮我们实现了封装SetMetadata

我们只需要,引入并替换掉原先的使用方式,与前文针对角色控制守卫效果一致。

image-20221126105034627

自定义参数装饰器

我们通过参数装饰器获取url

myrole.decorator.ts
import {
SetMetadata,
createParamDecorator,
ExecutionContext,
} from '@nestjs/common';
import type { Request } from 'express';

export const Myrole = (...args: string[]) => SetMetadata('myrole', args);

export const ReqUrl = createParamDecorator(
(data: string, ctx: ExecutionContext) => {
console.log(data, '自定义参数');

const req = ctx.switchToHttp().getRequest<Request>();
return req.url;
},
);

在控制器中使用

import { Myrole, ReqUrl } from './myrole/myrole.decorator';
xxxxxx
@Get()
@Myrole('admin')
findAll(@Query() query, @Headers() headers, @ReqUrl('hello') url) {
return url;
}

image-20221126105948673