省略字段以响应 GraphQL Apollo

Omitting the field in response with GraphQL Apollo

我正在使用 Apollo GraphQL 服务器和指令。

这是我的简单架构。注意令牌字段上的指令,用户类型。

const typeDefs = `
directive @allow(service: String) on FIELD_DEFINITION 

type User {
  email: String!
  pass: String!
  ... other fields here
  token: String  @allow(service: "login")
}

type Mutation {
  login(email: String!, pass: String!): User
}`;

我想 return 只有在调用登录时才使用令牌字段。否则,我想 return 没有令牌字段 的用户对象 ,我所能找到的只是抛出异常或 return 在 "token"字段。

class SkipDirective extends SchemaDirectiveVisitor {
  visitFieldDefinition(field, details) {
    const { resolve = defaultFieldResolver } = field;
    field.resolve = async function (...args) {
      // If called in context different from "login"
      // Here I would like to just "delete" the "token" field
      else {
        const result = await resolve.apply(this, args);
        return result;
      }
    };
  }
}

想法?

如果请求一个字段,则返回该字段时应返回与该字段类型匹配的值,否则返回 null。否则会破坏 spec.

您无法通过架构指令修改此行为。字段定义指令只能通过修改字段的解析器来更改运行时行为。但是,在调用解析器时,选择集已经确定,因此修改它为时已晚。返回 null 或抛出错误几乎是仅有的两个选项。

可能能够通过formatResponse选项或自定义插件实施某种解决方法。但是,由于此行为会违反规范,因此无法确定它是否会导致客户端库或其他工具出现问题。