Search code examples
expressgraphqlapollo

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]
}

I am getting validation errors:

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...

How do I implement this? The apollographql documentation says they support it, but no examples were given for these.


Solution

  • 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.

    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.