【问题标题】:Get access to headers in ValidatorConstraint访问 ValidatorConstraint 中的标头
【发布时间】:2020-06-23 18:07:32
【问题描述】:

我正在尝试编写一个自定义验证装饰器,该装饰器将禁止用户在单个类别/子类别中创建具有相同标题的条目。为此,我将使用类验证器库并编写如下装饰器:

@ValidatorConstraint({ name: 'isUniqueEntryTitle', async: true })
@Injectable()
export class IsUniqueEntryTitle implements ValidatorConstraintInterface {
    constructor(
        private readonly userService: UserService,
    ) {}

    public async validate(val: any, args: ValidationArguments): Promise<boolean> {
        return true;
    }

    public defaultMessage(args: ValidationArguments): string {
        return `Entry with such title already exists in this folder`;
    }
}

问题在于,我将不得不进行一个非常复杂的数据库查询来检查具有这种标题的条目是否已经在数据库中。我需要知道的参数之一显然是用户 ID,用户 ID 可以从用户 jwt 令牌中检索,但我如何在此类中访问它?这就是我现在遇到的问题。

【问题讨论】:

    标签: typescript nestjs


    【解决方案1】:

    您可以尝试将您的验证器设置为请求范围内可注入 (link on documentation)。

    这种方法允许您将 Request 实例注入验证器并通过它访问用户。

    简而言之,它看起来像

    import { REQUEST } from '@nestjs/core';
    
    @ValidatorConstraint({ name: 'isUniqueEntryTitle', async: true })
    @Injectable({ scope: Scope.REQUEST })
    export class IsUniqueEntryTitle implements ValidatorConstraintInterface {
        constructor(
            private readonly userService: UserService,
            @Inject(REQUEST) private request: Request
        ) {}
    
        public async validate(val: any, args: ValidationArguments): Promise<boolean> {
            return true;
        }
    
        public defaultMessage(args: ValidationArguments): string {
            return `Entry with such title already exists in this folder`;
        }
    }
    

    【讨论】:

    • 嗯听起来很有趣,让我试试吧。
    • 这似乎是一个不错的计划,但我刚刚尝试过,当我尝试通过this.request.headers 访问标题时,我收到一条错误消息:Cannot read property 'headers' of undefined,这意味着@987654327 @ 未定义。为什么会这样?
    • 也许 DI 容器不知道它应该注入哪个请求。尝试在班级顶部添加import { REQUEST } from '@nestjs/core';。 (我已经更新了答案)
    • 或者我错过了一些实现细节,请尝试按照这个 (docs.nestjs.com/fundamentals/injection-scopes) 指令进行操作
    • 我按照文档做了一切,你可以在这里查看stackoverflow.com/questions/62522438/… 但是没有成功。有什么想法吗?
    【解决方案2】:

    我没有得到你真正需要的东西。但为了方便您,您可以使用此模块 nestjs-dbvalidator 来检查 colmun 是否唯一或存在

    【讨论】:

    • 我正在使用名为 class-validator 的库,我非常不愿意添加其他库,因为某些技术没有做到 100% 整洁。感谢您的建议,但我想我会寻找一些解决方法。我需要的很简单,我需要访问这个类中的标题。我还没想好怎么做。
    • 你可以通过创建一个拦截器来将id_user添加到你的请求中并在你的DTO中添加一个属性,然后你可以通过console.log(args.object.id_user); 访问这个id,恐怕我没有'不能很好地向你解释,如果你想让我为你做一个例子,请随时告诉我。
    • 我完全理解你的意思。这实际上是我关于如何解决这个问题的最初想法之一,但我认为可能会有更好的想法,但现在似乎很清楚,这是这个 sh1tty 框架允许的唯一机会。上面的解决方案不起作用,地狱知道为什么。
    猜你喜欢
    • 1970-01-01
    • 2016-11-23
    • 2014-12-07
    • 1970-01-01
    • 1970-01-01
    • 2017-01-24
    • 1970-01-01
    • 2018-07-07
    • 2016-03-21
    相关资源
    最近更新 更多