Combine multiple “…” GraphQL fragments into one to be reused

Combine multiple “…” GraphQL fragments into one to be reused


0

I am using Gatsby and its GraphQL database.

I am noticing I am duplicating a lot of GraphQL fragments like this on multiple pages.

Here is an example of two queries:

query Page1 {
  pageData: page1Data {
    mainContent {
      ...Fragment1
      ...Fragment2
      ...Fragment3
      ...Fragment4
      ...Fragment5
    }
  }
}

query Page2 {
  pageData: page2Data {
    mainContent {
      ...Fragment1
      ...Fragment2
      ...Fragment3
      ...Fragment4
      ...Fragment5
    }
  }
}

Is there a way in GraphQL to combine all these ...Fragments into one?

Ideally:

mainContent {
      ...Fragment1
      ...Fragment2
      ...Fragment3
      ...Fragment4
      ...Fragment5
}

query Page1 {
  pageData: page1Data {
    mainContent {
     ...mainContent
    }
  }
}

query Page2 {
  pageData: page2Data {
    mainContent {
      ...mainContent
    }
  }
}

Or any other best practices to avoid query duplication?

1 Answer
1


0

GraphQL supports named fragments, which it looks like you’re already aware of. In the specification, a FragmentDefinition contains a SelectionSet, which in turn can include a FragmentSpread; that is, a named fragment definition can include other fragment references, provided there is not a circular loop of fragments.

fragment Fragments1to5 on MainContent {
  ...Fragment1
  ...Fragment2
  ...Fragment3
  ...Fragment4
  ...Fragment5
}

query Page1 {
  pageData: page1Data {
    mainContent { ...Fragments1to5 }
  }
}

Since the fragment definition does contain an arbitrary selection set, you’re can include nested fields and fragments too. If your goal is to not repeat things, you can also include the mainContent field in a fragment.

fragment MainContent on PageData {
  mainContent {
    ...Fragments1to5
  }
}

query Page2 {
  pageData: page2Data { ...MainContent }
}

(If you control the API definition as well, consider using field arguments to specify which page you’re getting. That would let you have a single top-level query controlled by a caller-provided argument, and you wouldn’t necessarily have to repeat the text of the query to fetch different pages.)



Leave a Reply

Your email address will not be published. Required fields are marked *