1

I'm calling an API where a field is optional and for some records it will not exists so it won't return e.g:

...
media_gallery {
    url
    label,
    ... on ProductVideo {
         video_content {
          video_url
       }
    }
 } 
 ...

In this case above video_content object for some record it will not return. I've searched the web and apply various possible fix but not luck, one being fragments and possible types ref:https://www.apollographql.com/docs/react/data/fragments/#fragment-matcher, apply all of them without errors but the issue still persists.

Anyone has any idea how to make apollo understand that this field is optional?

Thanks

1
  • Fragments are used to combine data from different pieces of your graph (e.g. if ProductVideo was a subset of another type). Your graph should return any available value that's returned via a resolver, the only requirement is to make the field nullable in the schema. If you share reproducible steps to re-create the issue there may be additional advice that could be shared as well.
    – Kyle
    Commented Jul 27, 2022 at 15:53

1 Answer 1

0

To use a fragment, first define the interface that each type implements to represent their relationship. As a minimal example:

"Represents media_gallery's common attributes"
interface media_gallery {
  url: String!
  "The media_gallery url"
  label: String!
  "The media_gallery label"
}

The implementing types will need to include these fields and return types, as well as the new fields they need:

type ProductVideo implements media_gallery {
  url: String!
  "The media_gallery URL"
  label: String!
  "The media_gallery label"
  video_content: String!
  "Product Video's description"
  video_url: String!
  "URL to the Product Video"
}

Once these are defined, create the necessary resolvers to determine which type matches the interface implementation returned. From there, fragment composition can be added:

"Declared fragment"
query getMediaGallery {
  media_gallery {
    url
    label
    ...ProductVideoContent
  }
}

fragment ProductVideoContent on ProductVideo {
  video_content {
    video_url
  }
}

"Inline fragment"
query getMediaGallery {
  media_gallery {
    url
    label
    ... on ProductVideo {
      video_content {
        video_url
      }
    }
  }
}

Some additional resources on using fragments: Apollo Odyssey tutorial for Intermediate Schema Design, dev doc on semantically meaningful interfaces, Using fragments with unions and interfaces.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.