Organizing GraphQL Calls in Contentful Follow Up

By: David Boland

Two devs sitting in front of a computer with the Nansen logo

Graphql

Contentful

This post is a follow up to a previous post about how to organize your GraphQL calls with fragments. The goal being to make a call to a Contentful multi reference field more concise.

Whenever we do this, we run into two potential problems. One is that we could end up with content entries of dozens of different types in that multi reference field. This would result in bloated GraphQL calls in our code. The second problem is that GraphQL throws an error if you add code for a type that is not in that reference field. This would mean that if you wanted to add a new type to that field, you would need to update the code every time. This solution aims to solve both those problems.

As I mentioned this is a follow up from my previous post on organizing your GraphQL calls. So if you would like more details, I would suggest looking there. Instead I am going to build off that last post. If you read it, you will know that we ended up with the following.

export const pageQuery = graphql`  
    query PageBySlug($slug: String!) {    
        contentfulStandardPage(slug: {eq: $slug}) {
        blocks {
          __typename
             ... on Node {
                 ... HeroBlock
                 ... TextBlock
        }
      }
    }
}
`;

With this we were able to incorporate fragments. This made our code more reusable, and minimized the amount of code we needed per GraphQL call.

While this was great, I got a comment from a reader asking if it was possible to clean it up even further. While the implementation helped, they had many content types and many multi reference properties. So they wanted a way to break it down even further.

The Fix

We were able to come up with the following. This allowed for one line of code per multi reference field called.

fragment Blocks on ContentfulEntry {
			__typename
            ... on Node {
              ... HeroBlock
              ... TextBlock
      }
}

Then you would reference your fragment in the following way:

export const pageQuery = graphql`  
    query PageBySlug($slug: String!) {    
        contentfulStandardPage(slug: {eq: $slug}) {
        blocks {
          ... Blocks
        }
      }
    }
}
`;

And that worked for them. After that, no matter how many reference fields you have, or types might be in them, you need one line of code.

I hope you found this helpful. If you have any follow up questions or thoughts please feel free to reach out.