Gatsby: Allow non-existing fields in GraphQL Queries

Gatsby: Allow non-existing fields in GraphQL Queries

I’m using Gatsby with the WordPress source plugin. So far so good. But the thing is I am querying fields that might or might not be there, in this case, the featured image of a post.
Here is my query:
{
allWordpressPost(sort: { fields: [date] }) {
edges {
node {
title
excerpt
slug
featured_media
better_featured_image {
wordpress_id
alt_text
caption
description
media_type
post
source_url
}
}
}
}
}

It works well when the featured image is set, but fails miserably otherwise.
And so my question: Is there any way in GraphQL to query an optional field? To add a default value to a required field?
I am all too new to GraphQL so I’m not even sure that’s possible at this point.
Thank you.

Solutions/Answers:

Solution 1:

This article explains the back story, but in short, you need to make sure that at least 1 of your WordPress posts has the featured image. Then the better_featured_image field will always exist.

In javascript, if you try to access allWordpressPost.edges.node.better_featured_image.wordpress_id and better_featured_image does not exist, you’ll get a syntax error.

Without knowing what “fails miserably” specifically means, not sure what else to suggest.

References

Related:  Relay-Modern FragmentContainer data not populated