4

I'm using Gatsby with Netlify CMS and have some optional fields in a file collection. The problem with this is that I'm unable to retrieve these fields using GraphQL, as the field doesn't exist if it was left blank.

For example, let's say I have the following collection file:

label: "Primary Color",
name: "primary",
file: "data/palette.yaml",
widget: "object",
fields: [
  {
    label: "Light",
    name: "light",
    required: false,
    widget: "string"
  },
  {
    label: "Main",
    name: "main",
    required: false,
    widget: "string"
  },
  {
    label: "Dark",
    name: "dark",
    required: false,
    widget: "string"
  },
  {
    label: "Contrast Text",
    name: "contrastText",
    required: false,
    widget: "string"
  }
]

All fields are optional. So let's say the user only enters in a value for main. This then saves the data as:

primary:
  main: '#ff0000'

light, dark and contrastText are not saved at all - they are simply left out entirely.

When I query the data in GraphQL, I obviously need to check for ALL fields since I have no idea which optional fields were filled in by the user and which were left blank. This means my query should be something like:

query MyQuery {
  paletteYaml {
    primary {
      light
      main
      dark
      contrastText
    }
  }
}

Using the above example where the user only filled in the main field, the above query will throw an error as light, dark and contrastText fields do not exist.

I am using a file collection type (as opposed to folder collection type) for this, so I can't set a default value. It wouldn't matter if I could set a default value anyway, since GraphQL and Yaml do not accept undefined as a value - they can only accept null or an empty string ("") as a best alternative.

Even if I manually save the yaml file with all field values set to null or "", this wouldn't work either as it would then cause additional issues as I am deep merging the query result with another javascript object.

I simply need to have GraphQL return undefined for each blank (missing) field instead of throwing an error, or not return the blank/missing fields at all.

This seems like a common issue (handling optional fields in Netlify CMS) but there is nothing in the documentation about it. How do people handle this issue?

Jake
  • 3,865
  • 5
  • 25
  • 58
  • This is a GraphQL/Gatsby issue, Netlify CMS just edits the data. I believe Gatsby's answer for this is the new Schema Customization API they released a while back: https://www.gatsbyjs.org/docs/schema-customization/ – Shawn Erquhart Nov 04 '19 at 17:16
  • Yep, that guide explains how to fix it. The issue is that the schema type definitions are automatically inferred however you can override that in gatsby-node.js. If you want to post this as an answer I'll mark it as accepted. – Jake Nov 06 '19 at 01:57

0 Answers0