如何在Apollo服务器中实现@include或@skip指令 [英] How do I implement the @include or @skip directive in apollo server

查看:80
本文介绍了如何在Apollo服务器中实现@include或@skip指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大数据集正在尝试.我试图有条件地包括嵌套对象.我的客户查询:

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 指令内置于

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆