node.js - NestJS、GraphQL、类验证器 - 在验证方法中访问请求对象

标签 node.js graphql nestjs class-validator nestjs-passport

我有一个自定义类验证器规则:

import { Injectable } from "@nestjs/common";
import { ValidatorConstraint, ValidatorConstraintInterface, ValidationArguments } from "class-validator";

@ValidatorConstraint({ name: "Foo", async: true })
@Injectable()
export class FooRule implements ValidatorConstraintInterface {    
    async validate(value: unknown, args: ValidationArguments) {
        // how to access request object from here?
    }
    
    defaultMessage(args: ValidationArguments) {
        return "NOT OK.";
    }
}

如何在 validate() 方法中访问请求对象?

最佳答案

我最终使用了自定义拦截器:

import { Injectable, NestInterceptor, CallHandler, ExecutionContext } from "@nestjs/common";
import { GqlExecutionContext } from "@nestjs/graphql";
import { ForbiddenError } from "apollo-server-core";
import { Observable } from "rxjs";

@Injectable()
export class FooInterceptor implements NestInterceptor {
    intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
        // get gql execution context from http one
        const gqlCtx = GqlExecutionContext.create(context);

        // holds data passed in a gql input
        const args: unknown[] = gqlCtx.getArgs();

        // req object (can be used to obtain jwt payload)
        const req = gqlCtx.getContext().req;

        // validation logic here
        const validationPassed = true;

        if (validationPassed) {
            // invoke the route handler method 
            return next.handle();
        }

        // will be caught by nest exceptions layer
        throw new ForbiddenError("Not allowed.");
    }
}

关于node.js - NestJS、GraphQL、类验证器 - 在验证方法中访问请求对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71253547/

相关文章:

postgresql - 通过 DBeaver 添加列时,Hasura (Graphql) 控制台中的 PostgreSQL 数据库不存在此类列

nestjs - 如何在带有嵌套 session 的守卫中使用 session 对象

NestJs 在多个模块中使用相同的服务实例

node.js - 模块 '"typeorm "' has no exported member ' DataSource' 和 'DataSourceOptions'

caching - 如何在 Express - Node.js 上激活缓存?

ios - API.swift 文件未更新 : Apollo GraphQL iOS

node.js - Mongoose 查询 : how to pass a variable

java - 不等待父 @GraphQLContext 解析器解析

javascript - Loopback中静态远程方法及其方法签名的定义

mysql同时插入?