是否在GraphQL模式中设置两个必填字段之一?
我正在使用GraphTool,但这可能是一个一般的GraphQL问题。有没有办法使两个字段中的一个成为必填字段 比如说我有一个帖子类型。帖子必须附加到组或事件。这可以在模式中指定吗是否在GraphQL模式中设置两个必填字段之一?,graphql,graphcool,Graphql,Graphcool,我正在使用GraphTool,但这可能是一个一般的GraphQL问题。有没有办法使两个字段中的一个成为必填字段 比如说我有一个帖子类型。帖子必须附加到组或事件。这可以在模式中指定吗 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 // 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
}
}
突变{
createPost(
正文:“这里有一条评论”,
作者:“,
事件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
}
}
突变{
createPost(
正文:“这里有一条评论”,
作者:“,
组ID:“”,
位置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
}
}
突变{
createPost(
正文:“这里有一条评论”,
作者:“,
组ID:“”,
){
身份证件
}
}
您无法根据需要定义模式来定义输入组——每个输入可以单独为null(可选)或非null(必需)
处理这种情况的唯一方法是在特定查询或变异的解析器中。例如:
(obj, {eventId, groupID, locationID}) => {
if (
(eventID && !groupID && !locationID) ||
(groupID && locationID && !eventID)
) {
// resolve normally
}
throw new Error('Invalid inputs')
}
看起来,为了使用GraphTool实现这一点,您必须使用自定义解析器 在模式中表示这一点的一种方法是,在您的情况下,它可以是这样的:
type LocatedGroup {
group: Group!
location: Location!
}
union Attachable = Event | LocatedGroup
type Post {
body: String!
author: User!
attachable: Attachable!
}
但是,您可以使用联合类型来解决此问题。我更喜欢@oneOf指令和相关的