如何在 apollo 服务器中实现 @include 或 @skip 指令 [英] How do I implement the @include or @skip directive in apollo server
问题描述
我有一个正在试验的大型数据集.我正在尝试有条件地包含嵌套对象.我的客户查询:
I have a big dataset I am experimenting with. I am trying to conditionally include nested objects. My client query:
query getAllAlbums ($fetchPhotos: Boolean!){
albums{
id
title
tags{
...Tag
weight
}
carouselItems{
id,
mediaUrl
}
photos @include(if: $fetchPhotos){
...Photo
}
}
}
我第一次尝试在服务器端实现,我将它添加到架构中:
For my first attempt at implementing on the server side, I added it to the schema:
type Album @include{
id: String
title: String
tags: [Tag]
photos: [Photo] @include(if: fetchPhotos)
carouselItems: [Photo]
}
我收到验证错误:
Error: Directive "@include" may not be used on OBJECT.
Directive "@include" argument "if" of type "Boolean!" is required, but it was not provided.
Directive "@include" may not be used on FIELD_DEFINITION.
好的,我不能在架构上使用它,那么还剩下什么?解析器?它不在参数中...
Okay, I can't use it on the schema, so what is left? The resolvers? It isn't in the arguments...
我该如何实现?apollographql 文档说他们支持它,但没有给出这些示例.
How do I implement this? The apollographql documentation says they support it, but no examples were given for these.
推荐答案
@skip
和 @include
指令内置于 GraphQL 规范本身.您无需在服务器端执行任何操作即可启用它们——它们将仅适用于任何符合规范的 GraphQL 服务器.
The @skip
and @include
directives are built into the GraphQL specification itself. You don't have to do anything server-side to enable them -- they will just work with any GraphQL server that is spec-compliant.
如果 @include
指令存在于字段或片段上并且 if
值为 false
,那么 GraphQL 运行时将简单地处理该字段或片段就好像它一开始就不存在一样(不会调用解析器,并且会从返回给客户端的结果中省略该字段).当 if
值为 true
时,同样适用于 @skip
指令.
If the @include
directive is present on a field or fragment and the if
value is false
, then the GraphQL runtime will simply treat that field or fragment as if it didn't exist in the first place (the resolvers won't be called and the field(s) will be omitted from the result returned to the client). The same applies to the @skip
directive when the if
value is true
.
这篇关于如何在 apollo 服务器中实现 @include 或 @skip 指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!