在 graphql 模式指令中,有什么方法可以检查预期的 return 字段是否不可为空

in a graphql schema directive, is there any way to check if the expected return field is non-nullable

我有一个执行数据库查询的模式指令,return是预期的结果。我使用此指令的某些字段是不可空的。这意味着如果有错误的用户输入,比如客户端要求一些不存在的数据,客户端将得到 "Can't return null for non nullable field" 一般异常。虽然这没关系,但如果我能抛出 UserInputError

会更好

当我在解析器中执行此操作时,因为我知道该字段是什么,所以我只需检查 return 值是否为 null 并抛出新的 UserInputError。在指令中我不知道该字段是否可以为空,所以我不知道什么时候 return null 或抛出。有办法检查吗?

代码如下:

export class QueryDirective extends SchemaDirectiveVisitor {
  visitFieldDefinition(field) {
    const { resolve = defaultFieldResolver } = field;
    const directiveArgs = { ...this.args };
    field.resolve = async function(obj, args, context, info) {
      const session = context.driver.session();
      let queryResult = await session.run(directiveArgs.statement, args);
      session.close();
      let result = extractResult(result, "result");
      // Any way to check here if field is non-nullable and throw new UserInputError?
      if (!directiveArgs.resolve) return resolve.call(this, result, args, context, info);
      else return result;
    };
  }
}

传递给 visitFieldDefinitionfield 对象的类型是 GraphField:

export interface GraphQLField<
  TSource,
  TContext,
  TArgs = { [key: string]: any }
> {
  name: string;
  description: Maybe<string>;
  type: GraphQLOutputType;
  args: GraphQLArgument[];
  resolve?: GraphQLFieldResolver<TSource, TContext, TArgs>;
  subscribe?: GraphQLFieldResolver<TSource, TContext, TArgs>;
  isDeprecated?: boolean;
  deprecationReason?: Maybe<string>;
  extensions: Maybe<Readonly<Record<string, any>>>;
  astNode?: Maybe<FieldDefinitionNode>;
}

因此您可以通过访问 field.type 来确定字段的类型。 Non-null 是一种包装器类型。如果字段不为空,field.type 将 return 一个 GraphQLNonNull 对象,其中 ofType 属性 引用包装类型。