GatsbyJs - How to handle empty graphql node from Contentful plugin

Viewed 1608

I am building a site in Gatsbyjs that pulls information in via the gatsby-source-contentful plugin, but I'm struggling with the graphql side of things.

If I have a Content model in Contentful that contains a field to override the default description for example - then if none of the content uses that yet graphql throws an error if I try to include it in my query.

Is there anyway to short circuit the graphql queries?

Examples

{
  allContentfulPage {
    edges {
      node {
        title
        description {
           description
        }
      }
    }
  }
}

This will break if there is no Page model that exists with a description, but as soon as one page gets a description it works.

2 Answers

The other solution would be to create and define the ContentfulPage type in your gatsby-node.js file. here is the link to gatsby documentation if you need to read more .

To create types you could add this to your gatsby-node.js file:

const createSchemaCustomization = ({ actions }) => {
  const types = [
    `
     type ContentfulPage implements Node {
       description : ContentfullDescription

     }
     type ContentfullDescription implements Node {
       description : String
     }
    `,
  ];

  actions.createTypes(types);
};

const gatsbyNode = {
  createSchemaCustomization,
};

export default gatsbyNode;

this is only the case if the description is a string, if it is some other type such as rich text you should add its type the createTypes api. then it would be:

const createSchemaCustomization = ({ actions }) => {
  const types = [
    `
     type ContentfulPage implements Node {
       description : ContentfullDescription

     }
     type ContentfullDescription implements Node {
       description : ContentfulRichText
     }
     type ContentfulRichText {
      raw: String
      references: [Node] @link(from: "references___NODE")
    }
    `,
  ];

  actions.createTypes(types);
};

const gatsbyNode = {
  createSchemaCustomization,
};

export default gatsbyNode;

Please take note that I am just guessing the type of description it might be some other types that you need to create yourself.

Related