1

我尽力在 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, args, context, 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;
4

0 回答 0