视频教程
nest new custom-decorator -p pnpm
pnpm start:dev
在Nestjs 中我们使用了大量装饰器 decorator ,所以Nestjs 也允许我们去自定义装饰器。
1. 自定义方法装饰器
nest g decorator aaa --flat
它生产的代码,这个就是Aaa就是我们自定义的装饰器
![](https://file.jishuzhan.net/article/1788205254848811009/032e2c931e92485938200d65e2591055.webp)
不知道大家还记不记得我们之前讲过的@SetMetadata,我们快速的回顾一下
nest g guard aaa --flat --no-spec
![](https://file.jishuzhan.net/article/1788205254848811009/511b19888248ceea17e74318df89bfb7.webp)
![](https://file.jishuzhan.net/article/1788205254848811009/d693e1f572931addfb8a107fe6ce99a2.webp)
![](https://file.jishuzhan.net/article/1788205254848811009/5c2ed07d0c7f1286f5ffbd261375bf10.webp)
上面就是我们通过nest提供的@SetMetadata装饰器,实现的角色控制守卫,但是不同 metadata 有不同的业务场景,有的是用于权限的,有的是用于其他场景的,这时候就可以在封装一层
我们修改下aaa.decorator
![](https://file.jishuzhan.net/article/1788205254848811009/d41919c7f84cc3afdadb21789591d5d1.webp)
在使用我们写的这个装饰器
![](https://file.jishuzhan.net/article/1788205254848811009/9e90e9d22a3bc11326c923dd265fc964.webp)
效果和之前一样
可以看到我们这里装饰太多了 ,那我们是不是可以自定义个装饰器,把他们整合到一起?
nest g d bbb --flat
![](https://file.jishuzhan.net/article/1788205254848811009/82708201c3f988824dc510d7e7b53d05.webp)
![](https://file.jishuzhan.net/article/1788205254848811009/f5958923669d728d6fc49935f28c425f.webp)
效果也是和之前的一致
2. 自定义参数装饰器
nest g d ccc --flat
![](https://file.jishuzhan.net/article/1788205254848811009/1f2b8e751ec016607945cbc15568ba91.webp)
data 是传入的参数。 ExecutionContext 前面讲过,可以取出 request、response 对象。
![](https://file.jishuzhan.net/article/1788205254848811009/343f1dd88680178876111c672a7c2994.webp)
![](https://file.jishuzhan.net/article/1788205254848811009/ea7fb6e9110f89825e03a610f0234492.webp)
参数装饰器的返回值就是参数的值
我们已经明白了nest中怎么定制参数装饰器了,那我们来实现一个它内置的参数装饰器-@Query
我们先复制一下刚刚的ccc.decorator改名为query.decorator,并修改如下
![](https://file.jishuzhan.net/article/1788205254848811009/ff068ff01d820d778a1772b65c7abe6b.webp)
![](https://file.jishuzhan.net/article/1788205254848811009/b327aa3a0b5d04dc7cd1c1e27281ae0c.webp)
![](https://file.jishuzhan.net/article/1788205254848811009/3f15570f2668173fac78a8987ce83f12.webp)
当然,你还可以使用pipe做参数验证和转换
![](https://file.jishuzhan.net/article/1788205254848811009/ddef71d70fff31750b2f8745d792ad35.webp)
![](https://file.jishuzhan.net/article/1788205254848811009/9a91454be3288dfcd226088b706c6ce3.webp)
3. 自定义类装饰器
类装饰器和方法装饰器的定义方式一样,比如:
![](https://file.jishuzhan.net/article/1788205254848811009/22fb723d1b8c9d9827412a736c65e201.webp)
![](https://file.jishuzhan.net/article/1788205254848811009/6dbdcabf71df8d662a08fff7e7fdaec2.webp)