Querying Global Fields in Craft CMS with CraftQL and Gatsby JS

945 Views Asked by At

I am using Craft in headless mode with the CraftQL plugin. My front end is built using Gatsby JS.

I am able to query entries and output the data to my templates, however Global fields are not available. Here is my code:

// gatsby-config.js
plugins: [
  {
        resolve: `gatsby-source-craftcms`,
        options: {
            endpoint: `http://cms.local/api`,
            token: `REDACTED`,
            query: `{
                globals: globals {
                    contact {
                        address
                    }
                },
                home: entries(section:[home]) {
                    id
                    title
                    ... on Home {
                        subHeading
                        intro
                        ctaButton {
                            ... on CtaButtonButton {
                                __typename
                                text
                                linkUrl
                            }
                        }
                    }
                },
// etc

And then in my template:

export const query = graphql`
  query {
    home {
        title
        subHeading
        intro
        ctaButton {
            text
            linkUrl
        }
    }
    globals {
        contact {
            address
        }
    }
  }
`

In my console I get:

error  Cannot query field "global" on type "Query"

If I remove the global from the query I can successfully build and output data.home.title.

I've tried using the CraftQL browser in the CMS and I can successfully query globals:

enter image description here

I'm confident I'm missing something but can find nothing in the docs for Gatsby-Source-Craft or CraftQL.

Anyone have any idea what I'm doing wrong here??

1

There are 1 best solutions below

0
On

So having spoken to the maker of CraftQL yesterday, my mistake was assuming I needed to use gatsby-source-craftcms as my source plugin. In actual fact, the standard gatsby-source-graphql was much better and more abstract, meaning you don't need to construct giant graphQL queries in the gatsby-config. Also the docs for it are much better explained.

now my gatsby-config.js looks like this:

plugins: [
    {
        resolve: `gatsby-source-graphql`,
        options: {
    typeName: "Craft",
    fieldName: "craft",
    // Url to query from
    url: "http://cms.local/api",
    // HTTP headers
    headers: {
      Authorization: `bearer ACCESSTOKENHERE`,
    }
        },
    },

and my query looks like this

{
  craft {
    globals {
      contact {
        address
      }
    }
  }
}

which is much more sane and closer the the normal Twig API

You can view the Twitter exchange here