1
votes

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.

1
Where exactly is it failing? The Query or the Render?Scriptonomy
@Scriptonomy The query. When the field is not found.Unforgiven
You might have luck with the schema explorer in the GraphiQL at localhost:8000/___graphqlchmac

1 Answers

2
votes

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.