使 GraphQL 模式中的两个字段之一成为必需的?

Eva*_*nss 10 graphql graphcool

我正在使用 Graphcool 但这可能是一个通用的 GraphQL 问题。有没有办法使两个字段之一成为必需的?

例如说我有一个 Post 类型。帖子必须附加到组或事件。这可以在模式中指定吗?

type Post {
  body: String!
  author: User!
  event: Event // This or group is required
  group: Group // This or event is required
}
Run Code Online (Sandbox Code Playgroud)

我的实际需求有点复杂。帖子可以附加到事件,也可以附加到组和位置。

type Post {
  body: String!
  author: User!
  event: Event // Either this is required, 
  group: Group // Or both Group AND Location are required 
  location: Location 
}
Run Code Online (Sandbox Code Playgroud)

所以这是有效的:

mutation {
  createPost(
   body: "Here is a comment",
   authorId: "<UserID>",
   eventId: "<EventID>"
  ){
    id
  }
}
Run Code Online (Sandbox Code Playgroud)

就像这样:

mutation {
  createPost(
   body: "Here is a comment",
   authorId: "<UserID>",
   groupID: "<GroupID>",
   locationID: "<LocationID>"
  ){
    id
  }
}
Run Code Online (Sandbox Code Playgroud)

但这不是:

就像这样:

mutation {
  createPost(
   body: "Here is a comment",
   authorId: "<UserID>",
   groupID: "<GroupID>",
  ){
    id
  }
}
Run Code Online (Sandbox Code Playgroud)

Dan*_*den 6

您无法定义架构以根据需要定义输入组——每个输入单独可以为空(可选)或非空(必需)。

处理这种情况的唯一方法是在特定查询或突变的解析器中。例如:

(obj, {eventId, groupID, locationID}) => {
  if (
    (eventID && !groupID && !locationID) ||
    (groupID && locationID && !eventID)
  ) {
    // resolve normally
  }
  throw new Error('Invalid inputs')
}
Run Code Online (Sandbox Code Playgroud)

看起来为了使用 Graphcool 做到这一点,您必须使用自定义解析器。有关更多详细信息,请参阅文档