gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 17:43:12 27 4
gpt4 key购买 nike

我正在使用 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
}
}

最佳答案

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

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

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

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

关于graphql - 使 GraphQL 模式中的两个字段之一成为必需的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48476154/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com