GraphQL Fragment Include being used inside GraphiQL IDE.

A module to include fragments inside a GraphQL query, using the following syntax: # include path.gql.

This module is useful when:

  • You have a collection of paragraphs (or any other kind of entity) that is being used by multiple Content Types.
  • GraphQL is used to export content data (ideally by using Static Suite module) and you find the same repeated data structure on multiple queries.

To avoid having to repeat the same query for every content type, you should:

  • use GraphQL fragments
  • extract them to files
  • use this module to include those fragment files into your GraphQL queries.

This module transforms the following:

# include Image.gql
{
  content:nodeById(id: "1") {
    id: entityId
    ... on NodeArticle {
      title
      image: fieldImage {
        entity {
          ...Image
        }
      }
    }
  }
}

into this:

# sample content from Image.gql
fragment Image on MediaImage {
  entityLabel
  ... on MediaImage {
    mediaImage: fieldMediaImage {
      alt
      title
      url
      width
      height
    }
    credit: fieldImageCredit
    caption: fieldImageCaption
  }
}

{
  content:nodeById(id: "1") {
    id: entityId
    ... on NodeArticle {
      title
      image: fieldImage {
        entity {
          ...Image
        }
      }
    }
  }
}

How it works

  • Configure fragments base directory at /admin/config/graphql/fragment-include/config. That is were your fragment files are located. It's usually a directory inside /sites/default/.
  • Create a file inside the above directory, with the contents of your fragment, and with .gql extension. You can create subdirectories and include a fragment inside another fragment (infinite recursion protection is available).
  • Add an include to a GraqhQL query, using the following format: # include {RELATIVE_PATH_TO_FILE_INSIDE_FRAGMENTS_BASE_DIR}.gql
  • Execute the query, and the contents from the fragment file will be appended to the query before execution.

Debugging

If a fragment can not be found, a warning message is logged. Use dblog to view them.

Caveats

  • Due to the fact that the GraphQL specification does not support any kind of includes, we use comments and a syntax that is completely custom (# include path.gql). You can change that syntax to your convenience, extending graphql_fragment_include.graphql_fragment_loader service.
  • For the same above reason, GraphiQL IDE will remove the above comments when clicking "Prettify" button.

TODO

  • Find a way to maintain fragment includes when clicking GraphiQL's "Prettify" button.
Supporting organizations: 

Project information

Releases