创建GraphQL架构中需要两个字段之一?

时间:2018-01-27 13:13:17

标签: 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
}

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

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
  }
}

2 个答案:

答案 0 :(得分:2)

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

处理此类场景的唯一方法是在特定查询或突变的解析器中。例如:

function foo()
{
  for (i in arguments) 
  { 
    console.log(arguments[i]); 
  }
}
foo('str','wasdf',9)

看起来为了用Graphcool做到这一点,你必须使用自定义解析器。 See the documentation for more details

答案 1 :(得分:2)

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

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

union Attachable = Event | LocatedGroup

type Post {
  body: String!
  author: User!
  attachable: Attachable!
}