Skip to main content

Beginning the build of a GatsbyJS theme

Published on Friday 6, December 2019

I finally have my workspace set up, allowing me to begin serving content from one Drupal Commerce API server to three GatsbyJS apps. Next is building my first GatsbyJS theme. It's weird that they're called themes because it's like a module in Drupal. It provides functionality, data modeling, and content. 🤷‍♂️Then again, themes in WordPress are basically distributions.

So, I first set out to find examples. I assumed (correctly) that someone else has been down this road. Third & Grove made gatsby-theme-drupal. What is great is that they solved one major problem that I was not sure how to handle. Drupal Commerce heavily utilizes entity bundles. You can have different product types, and these product types may or may not support multiple variations. GraphQL creates schema types based on each entity and bundle.

What they do is query the bundles for an entity. With this data, they then determine the GraphQL schema name for the entity bundle content to create pages.

      const productTypes = await graphql(`{
        allCommerceProductTypeCommerceProductType {
          nodes {
            id
            label
            drupal_internal__id
            variationType
            multipleVariations
          }
        }
      }`);

I actually ended up finding a slight bug. If there is an entity type with a bundle and no entities for that bundle, it crashes. That is because there is no content to query and infer the schema from. I opened a pull request to add a check: https://github.com/thirdandgrove/gatsby-theme-drupal/pull/5.

This allowed me to generate 45 pages of products between all product types.

gatsbyjs 4040 page

The multiple variation flag in product types helps determine if a product's variations have attribute values. Such as color and size. With this query approach, we can assign templates properly. A product without variations has a simple add to cart form - its just a button! One with variations needs to have options for each attribute value.

Luckily we can provide two templates

  const simpleProductTemplate = require.resolve('./src/templates/simpleProductTemplate.js');
  const variationsProductTemplate = require.resolve('./src/templates/variationsProductTemplate.js');

And then, in gatsby-node for the theme, we can assign pages for products to the proper template.

createPage({
  path: element.path.alias,
  component: productType.multipleVariations ? variationsProductTemplate : simpleProductTemplate,
  context: {
    element,
    nodeName: productTypeNodeName
  }
})

And now, the templates can have GraphQL plugged in to build the pages out!

product graphiql output