Refractor GraphQL common code, similar to fragments...?

So for every structured text field I have to repeat something like this for internal record links in the GraphQL query:

description {
  blocks
  value
  links {
    __typename
    ... on ProductRecord {
      id
      slug
      title
      subtitle
    }
    ... on ProductCategoryRecord {
      id
      slug
      name
    }
    ... on SolutionRecord {
      id
      slug
      title
      subtitle
    }
    ... on SolutionCategoryRecord {
      id
      slug
    }
    ... on BlogPostRecord {
      id
      slug
      name,
      category {
        slug
      }
    }
    ... on BlogCategoryRecord {
      id
      slug
      name
    }
    ... on PageRecord {
      id
      slug
      title
    }
  }
}

Is there a way to add the links {} part into a fragment or something similar?

@primoz.rome if I’m understanding your question correctly, then I think you can turn links into a fragment and everything will be intelligently merged. Here’s my code for example:

I have the StructuredText field within its own fragment, which is then consumed by various queries:

fragment PostRecordBody on PostRecord {
  body {
    value
    blocks {
      ... on ImageBlockRecord {
        ...ImageBlockRecordFields
      }
      ... on TableOfContentsBlockRecord {
        ...TableOfContentsBlockRecordFields
      }
      ... on AsideBlockRecord {
        ...AsideBlockRecordFields
      }
      ... on SourcesBlockRecord {
        ...SourcesBlockRecordFields
      }
    }
  }
  ...PostRecordBodyLinks
}

And PostRecordBodyLinks is another fragment that looks like:

fragment PostRecordBodyLinks on PostRecord {
  body {
    links {
      ... on ProductRecord {
        __typename
        id
        name
      }
      ... on SocialMediaLinkRecord {
        __typename
        id
        name
      }
      ... on PostRecord {
        ...PostRecordCoreFields
      }
      ... on PageRecord {
        __typename
        id
        slug
      }
    }
  }
}

Everything works as I would expect, though I haven’t done detailed testing.

Best,
Taylor

2 Likes