Search code examples
graphqldrycontentful

How to get the same object properties from different items in Graphql


I'm using Contentful and it's Graphql. I have a collection, that has reference to different content types, like: page, landing, format, static page etc. The content types are different, but has some overlap. I want to get name and slug from each entry, but I want to know if I can do this without

...on Page {
  name
  slug
}
...on Landing {
  name
  slug
}
...on Static_Contante {
  name
  slug
}
etc. 

is there something like:

...on GenericCommonFields {
  name
  slug
}

I read about fragments, but I don't see if and how I should use them here. Should I just repeat the code, or is there better way?


Solution

  • You can solve it with fragments. First is to create fragment with all common item's parts like that:

    fragment commonCollectionItems on SectionBlocksItem {
     ...on Page {
       name
       slug
     }
     ...on Landing {
       name
       slug
     }
     ...on Static_Contante {
       name
       slug
     }
    }
    

    And use it in your collection like:

    someCollection {
     items {
      ...commonCollectionItems
      ... on Page { #example
       seoUrl 
       seoTitle 
      }
     }
    }