小满nestjs(第二十二章 nestjs 自定义装饰器)

在Nestjs 中我们使用了大量装饰器 decorator ,所以Nestjs 也允许我们去自定义装饰器。

 案例1 自定义权限装饰器

生成装饰器 

nest g d [name]
import { SetMetadata } from '@nestjs/common';

export const Role = (role: string[]) => {
    console.log(role,1)
    return SetMetadata('role', role);
}

 案例2 自定义参数装饰器返回一个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
})

猜你喜欢

转载自blog.csdn.net/qq1195566313/article/details/127179126