微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

用于检查两个或多个字段值的自定义指令

如何解决用于检查两个或多个字段值的自定义指令

我尽力在 Apollo Server Express 中编写自定义指令来验证两个输入类型字段。 但是代码甚至可以工作,但是已经发生了突变的记录。 如果有人可以帮助我修复下面代码中的任何错误,我将不胜感激。 这只是示例代码,我需要同时测试两个字段中的值。

const { SchemaDirectiveVisitor } = require('apollo-server');
const { GraphQLScalarType,GraphQLNonNull,defaultFieldResolver } = require('graphql');

class RegexDirective extends SchemaDirectiveVisitor {
  visitInputFieldDeFinition(field) {
    this.wrapType(field);
  }

  visitFieldDeFinition(field) {
    this.wrapType(field);
  }

  wrapType(field) {
    const { resolve = defaultFieldResolver } = field;
    field.resolve = async function (source,args,context,info) {
      if (info.operation.operation === 'mutation') {
        if (source[field.name] === 'error') {
          throw new Error(`Find error: ${field.name}`);
        }
      }
      return await resolve.call(this,source,info);
    };

    if (
      field.type instanceof GraphQLNonNull
      && field.type.ofType instanceof GraphQLScalarType
    ) {
      field.type = new GraphQLNonNull(
        new RegexType(field.type.ofType),);
    } else if (field.type instanceof GraphQLScalarType) {
      field.type = new RegexType(field.type);
    } else {
    //  throw new Error(`Not a scalar type: ${field.type}`);
    }
  }
}
class RegexType extends GraphQLScalarType {
  constructor(type) {
    super({
      name: 'RegexScalar',serialize(value) {
        return type.serialize(value);
      },parseValue(value) {
        return type.parseValue(value);
      },parseLiteral(ast) {
        const result = type.parseLiteral(ast);
        return result;
      },});
  }
}

module.exports = RegexDirective;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。