11

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

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

type Post {
  body: String!
  author: User!
  event: Event // This or group is required
  group: Group // This or event is required
}

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

type Post {
  body: String!
  author: User!
  event: Event // Either this is required, 
  group: Group // Or both Group AND Location are required 
  location: Location 
}

所以这是有效的:

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

就像这样:

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

但这不是:

就像这样:

mutation {
  createPost(
   body: "Here is a comment",
   authorId: "<UserID>",
   groupID: "<GroupID>",
  ){
    id
  }
}
4

2 回答 2

6

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

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

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

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

于 2018-01-28T04:49:09.880 回答
2

在模式中表示这一点的一种方法是使用unions,在您的情况下,它可能是这样的:

type LocatedGroup {
  group: Group!
  location: Location!
}

union Attachable = Event | LocatedGroup

type Post {
  body: String!
  author: User!
  attachable: Attachable!
}
于 2020-06-19T08:40:39.407 回答