GraphQL fragments throws errors if entry is not of this type

Hi!

I’m building a static site with gatsby and using the graphql-api from contentful. It is really nice, but I run into a problem with quering relations.

I have a Content Type (Channel) with a Many-Reference-Field in it. This field can contain M Entries which are not limited to one specific Content Type. In other words, this field “Linklist” can contain several different Content Types, but sometimes maybe only one or two.

When I query one specific Channel-Entry, I want to use fragments to get some details about the linklist-entries. But this throws errors if the linklist doesn’t contain the expected types.

I understand, that this is a bit complicated, but maybe this will help :slight_smile:

query MyQuery {
  contentfulChannel(slug: {eq: "my-channel"}) {
    title
    linklistEntries {
      ... on ContentfulChannel {
        title
      }
      ... on ContentfulSectionDefault {
        title
      }
    }
  }
}

This query will work, if linklistEntries contains both Channel- and SectionDefault-Types. But it will fail if it only contains Channel for example, or maybe others.

Many thanks in advance!

I found the solution! I only had to warp the fragments into ... on Node { --- } like this:

query MyQuery {
  contentfulChannel(slug: {eq: "my-channel"}) {
      contentful_id
      title
      linklistEntries { 
      ... on Node {
        ... on ContentfulChannel {
          title
          slug
        }
        ... on ContentfulSectionDefault {
          title
          slug
        }
      }
  }
}

This way, it doesn’t matter if the ContentType is available in linklistEntries.

Many thanks to Ville Halminen: