Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
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, extendinggraphql_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
- Module categories: Decoupled
- Ecosystem: GraphQL
- 10 sites report using this module
- Created by albertosilva on , updated
- Stable releases for this project are covered by the security advisory policy.
Look for the shield icon below.
Releases
8.x-1.7
released 7 September 2023
Works with Drupal: >=9
✓ Recommended by the project’s maintainer.
Install:
Development version: 8.x-1.x-dev updated 6 Sep 2023 at 21:40 UTC