有条件地省略NULL变量上的GraphQL字段
下面的查询有条件地省略NULL变量上的GraphQL字段,graphql,Graphql,下面的查询 query UserPosts($postId: ID) { currentUser { id name } post(id: $postId) { id title } } 这将生成此错误 类型为“ID”的变量“$postId”用于预期类型为“ID!”的位置 这很公平,因为id是post的必填字段。但是,在客户机中,我想将此设置为可选设置,如果$postId为null,只需返回null 一种解决方案是使用@include指令。但是
query UserPosts($postId: ID) {
currentUser {
id
name
}
post(id: $postId) {
id
title
}
}
这将生成此错误
类型为“ID”的变量“$postId”用于预期类型为“ID!”的位置
这很公平,因为id
是post
的必填字段。但是,在客户机中,我想将此设置为可选设置,如果$postId
为null
,只需返回null
一种解决方案是使用@include
指令。但是,它不支持条件。例如,这不起作用
接下来,您可能会想,为什么不包含布尔值呢?比如说
query UserPosts($postId: ID, $includePost: Boolean!) {
currentUser {
id
name
}
post(id: $postId) @include(if: $includePost) {
id
title
}
}
这也不起作用,因为需要ID
,即ID代码>。如果我使用ID相反,如果设置$includePost:false
,我将无法跳过需要$postId
是否可以使用GraphQL解决此场景
query UserPosts($postId: ID, $includePost: Boolean!) {
currentUser {
id
name
}
post(id: $postId) @include(if: $includePost) {
id
title
}
}