Express 用于检查输入类型的列表长度的自定义指令

Express 用于检查输入类型的列表长度的自定义指令,express,graphql,apollo,apollo-server,graphql-tools,Express,Graphql,Apollo,Apollo Server,Graphql Tools,我尽力在apollo server express中编写一个自定义指令,以验证[Int]类型的输入类型字段是否不超过最大长度,但不知道这样做是否正确。如果有人能帮我纠正下面代码中的任何错误,我将不胜感激 // schema.js directive @listLength(max: Int) on INPUT_FIELD_DEFINITION input FiltersInput { filters: Filters } input Filters { keys:

我尽力在apollo server express中编写一个自定义指令,以验证[Int]类型的输入类型字段是否不超过最大长度,但不知道这样做是否正确。如果有人能帮我纠正下面代码中的任何错误,我将不胜感激

// schema.js
directive @listLength(max: Int) on INPUT_FIELD_DEFINITION

  input FiltersInput {
    filters: Filters
  }

  input Filters {
    keys: [Int] @listLength(max: 10000)
  }

// Custom directive
const { SchemaDirectiveVisitor } = require('apollo-server-express');
import {
  GraphQLList,
  GraphQLScalarType,
  GraphQLInt,
  Kind,
  DirectiveLocation,
  GraphQLDirective
} from "graphql";

export class ListLengthDirective extends SchemaDirectiveVisitor {
  static getDirectiveDeclaration(directiveName) {
    return new GraphQLDirective({
      name: directiveName,
      locations: [DirectiveLocation.INPUT_FIELD_DEFINITION],
      args: {
        max: { type: GraphQLInt },
      }
    });
  }
  // Replace field.type with a custom GraphQLScalarType that enforces the
  // length restriction.
  wrapType(field) {
    const fieldName = field.astNode.name.value;
    const { type } = field;
    if (field.type instanceof GraphQLList) {
      field.type = new LimitedLengthType(fieldName, type, this.args.max);
    } else {
      throw new Error(`Not a scalar type: ${field.type}`);
    }
  }

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

class LimitedLengthType extends GraphQLScalarType {
  constructor(name, type, maxLength) {
  super({
      name,

      serialize(value) {
        return type.serialize(value);
      },

      parseValue(value) {
        value = type.serialize(value);

        return type.parseValue(value);
      },

      parseLiteral(ast) {
        switch (ast.kind) {
          case Kind.LIST:
            if (ast.values.length > maxLength) {
              throw {
                code: 400,
                message: `'${name}' parameter cannot extend ${maxLength} values`,
              };
            }
            const arrayOfInts = ast.values.map(valueObj => parseInt(valueObj['value']));
            return arrayOfInts;
        }
        throw new Error('ast kind should be Int of ListValue')
      },
    });
  }
}
这个看起来对吗

谢谢