4

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.

Rouven Weßling
  • 611
  • 4
  • 16

2 Answers2

2

Gatsby pulls data from Contentful and then it builds an internal "model" of what the data from Contenful looks like. The Contentful API is REST but internally Gatsby uses GraphQL.

If a field does not have a value on Contentful then it will not be a part of the generated GraphQL query in Gatsby. The solution is to push a single value in one of your records.

chmac
  • 11,757
  • 3
  • 32
  • 36
1

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.

Jaber Askari
  • 133
  • 6