【问题标题】:Nestjs extend/combine decorators?Nestjs 扩展/组合装饰器?
【发布时间】:2020-06-26 18:14:56
【问题描述】:

我有简单的自定义装饰器:

export const User: () => ParameterDecorator = createParamDecorator(
  (data: any, req): UserIdentity => {
    const user = getUser(req);
    return user;
  },
); 

现在,我需要验证 email 是否包含在 user 对象中。

问题是我无法更新我当前的装饰器。

我可以扩展我当前的装饰器吗?

在前一个的基础上创建一个新的装饰器还是创建一个新的装饰器并组合它?

【问题讨论】:

    标签: node.js typescript decorator nestjs


    【解决方案1】:

    是的,您可以使用 Nest 执行 "decorator composition",但这可能不是您的情况的完美解决方案,这取决于您打算在 user 没有 email 属性时执行的操作。

    根据文档中的示例:

    import { applyDecorators } from '@nestjs/common';
    
    export function Auth(...roles: Role[]) {
      return applyDecorators(
        SetMetadata('roles', roles),
        UseGuards(AuthGuard, RolesGuard),
        ApiBearerAuth(),
        ApiUnauthorizedResponse({ description: 'Unauthorized"' }),
      );
    }
    

    在本例中,Auth 是一个装饰器,可用于组合所有传入 applyDecorators 的装饰器。


    因此,我建议使用a pipe扩展您的装饰器。

    如文档所述:

    Nest 以与内置参数(@Body()、@Param() 和 @Query())相同的方式处理自定义参数装饰器。这意味着也为自定义注释参数执行管道(在我们的示例中,用户参数)。此外,您可以将管道直接应用于自定义装饰器:

    @Get()
    async findOne(@User(new ValidationPipe()) user: UserEntity) {
      console.log(user);
    }
    

    在本例中,User 是一个自定义参数装饰器。并且ValidationPipe 已通过,但您可以想象通过任何pipe

    【讨论】:

    • 谢谢回答。不幸的是,我现在无法扩展当前的装饰器(它在另一个项目中,我们将它用作 npm 包)。我使用了 applyDecorators,它就像一个魅力。
    猜你喜欢
    • 1970-01-01
    • 2016-07-18
    • 1970-01-01
    • 2016-08-18
    • 2017-11-19
    • 1970-01-01
    • 2021-05-19
    • 2013-02-19
    • 2017-03-06
    相关资源
    最近更新 更多