Search code examples
graphqlgatsby

How to define an optional field in graphQL fragment for query


Tha database for that queries comes up to a set of YAML files in a folder.

Using GatsbyJS theses files are collected and are available by graphQL requests.

Not all source files defines a label field.

Is it possible to return a default or empty value for that field when missing?


Actually I get following error:

Cannot query field "label" on type "EngagementsYamlTo".


This is my query:

{
  stable: allEngagementsYaml(filter: {stable: {eq: true}, to: {}}) {
    edges {
      ...engagementNode
    }
  }
  unstable: allEngagementsYaml(filter: {stable: {eq: false}}) {
    edges {
      ...engagementNode
    }
  }
}

fragment engagementNode on EngagementsYamlEdge {
  node {
    heading
    description
    iconClass
    stable
    to {
      href
      label
    }
  }
}

Solution

  • Hm ... that was not a problem of the query.

    None of the source files had a label field, so that schema was never touched. Having at least 1 file with label field will return a valid response.

    Clarified for this case!