Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough
Nov 18 2020
Nov 18

In Gatsby you use GraphQL to query data from your backend, the source plugin you use will allow you to access data from your source API. The gatsby_source_drupal plugin pulls data from Drupal JSON:API so it’s queryable with GraphQL inside your Gatsby app, while gatsby_source_graphql is just a wrapper around any backend GraphQL schema. This means we get access to the schema in the GraphQL 3 module for Drupal instead of the one defined in the gatsby_source_drupal plugin.

Let's compare some common query examples from both of these methods.

The queries here are kept simple to focus on specific elements and context.

Lets get a list of 3 nodes of type Article for a link list. Make sure they are published and sorted by sticky and changed.

JSON:API allNodeArticle

Query


query {
  allNodeArticle(
    filter: {
      status: {
        eq: true
      }
    }
    sort: {
      fields: [sticky, changed]
      order: [DESC, DESC]
    }
    skip: 0
    limit: 3
  ) {
    edges {
      node {
        drupal_internal__nid
        title
        path {
          alias
        }
      }
    }
  }
}

Query


query {
  drupal {
    nodeQuery(
      filter: {
        conditions: [
          { field: "status", value: "1" }
          { field: "type", value: "article" }
        ]
      }
      sort: [
        { field: "sticky", direction: DESC }
        { field: "changed", direction: DESC }
      ]
      offset: 0
      limit: 3
    ) {
      entities {
        ... on Drupal_NodeArticle {
          nid
          title
          path {
            alias
          }
        }
      }
    }
  }
}

The main difference I see in the query is how the filter and sort parameters work. With gatsby_source_drupal we have a set of filters for fields defined on the entity type; id, langcode, status, title, etc.

With gatasby_source_graphql and the GrapqhQL module I'm able to use "conditions" the way I would with EntityQuery in Drupal, working in PHP. For instance, I could filter my list of nodes by taxonomy term by adding a condition for that field.


...
    nodeQuery(
      filter: {
        conditions: [
          { field: "status", value: "1" }
          { field: "type", value: "article" }
          { field: "field_tags.entity.name", value: "sailboat"}
        ]
      }
    }
...

I could do this in gatsby_source_drupal as well, but it looks like:


...
  allNodeArticle(
    filter: {
      status: {
        eq: true
      }
      relationships: {
        field_tags: {
          elemMatch: {
            name: {
              eq: "sailboat"
            }
          }
        }
      }
    }
...

It might just be because I come from the backend first that I find the nodeQuery way more intuitive. I like that you can customize the query with conditions, conjunctions and groups. https://drupal-graphql.gitbook.io/graphql/queries/filters

Sometimes I use the Drupal Paragraphs module to make flexible columns of text. In this very simple example I've named the paragraphs field field_components and there are 2 types of paragraphs:

  • Columns: has one field field_components, another paragraph reference field.
  • Text: has field_heading and field_text

On my Article content type I added a paragraphs field called "field_components" as well. I can create an article with a "Columns" paragraph and inside the "Columns" paragraph I can add "Text" paragraphs. The Columns paragraph becomes a wrapper and can be styled to cause the nested Text paragraphs to layout as columns.

In the query, I've aliased the paragraph fields to "column_wrapper" and "columns", so it's a little clearer than field_components in the data.

JSON:API nodeArticle

Query


query($id: Int!) {
  nodeArticle(drupal_internal__nid: { eq: $id }) {
    relationships {
      column_wrapper: field_components {
        ... on paragraph__columns {
          relationships {
            columns: field_components {
              ... on paragraph__text {
                field_heading {
                  processed
                }
                field_text {
                  processed
                }
              }
            }
          }
        }
      }
    }
  }
}

Query


query($id: String!) {
  drupal {
    nodeById (
      id: $id
    ) {
      ... on Drupal_NodeArticle {
        column_wrapper: fieldComponents {
          entity {
            ... on Drupal_ParagraphColumns {
              columns: fieldComponents {
                entity {
                  ... on Drupal_ParagraphText {
                    fieldHeading {
                      processed
                    }
                    fieldText {
                      processed
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

You can see some differences in the way the schema identifies the fields. One uses relationships and field_components while the other uses fieldComponents and entity

JSON:API: nodeArticle has arguments for all the node fields; langcode, status, created, etc. while the GraphQL nodeById has only id and langcode. But if you're not looking for a specific node id and want to filter on something else, use the more flexible nodeQuery.

In my previous post I talked about using Drupal to process and serve derivative images instead of having Gatsby process them all at build time, which can take a very long time as the number of posts/images grows.

I compared the two source queries for this as well, and I think the differences are significant in this case. You can review that post for the details but I'll briefly summarise.

The goal was to load a set of image styles from an image field. To do this with gatsby_source_drupaland the JSON:API requires an additional Drupal contrib module to expose the images styles. The GraphQL module just handles it with derivative(style: [name]) on the field. Which can be aliased to query all the styles you wish.


...
  fieldImage {
    small: derivative(style: small) {
      width
      url
    }
    medium: derivative(style: medium) {
      width
      url
    }
    ...

The resulting data from GraphQL was easier to process, while the structure of the data from the JSON:API version kind of didn't make sense and required some extra massaging.

In general the gatsby-source-drupal plugin gives us queries in the form of "entityBundle" or "allEntityBundle" like the following:

  • nodeArticle, allNodeArticle
  • paragraphColumns, allParagraphColumns
  • taxonomyTermTags, allTaxonomyTermTags

These take arguments mapped to the entity fields.

The GraphQL module instead provides us with entity queries on each entity type that we can use just like an EntityQuery in Drupal PHP, as well as entityById and entityRevsionById.

  • queryNode, nodeById, nodeRevisionById
  • queryUser, userById
  • blockContentQuery, blockContentById, blockContentRevisionById

So far I've been able to do the things I want with either solution, but I find myself favoring GraphQL module. I assume that's from my backend roots. Lucky for us the GraphQL Explorer makes it all pretty easy to explore. Please let me know in the comments if I've said anything preposterous, or if you have any additional insights. Thanks for reading!

"Code like nobody is watching... but then refactor. ;)"

Sep 16 2020
Sep 16

Gatsby Image, along with gatsby-transformer-sharp and gatsby-plugin-sharp, is a common way to handle images in a Gatsby project.  It gives us the power to process source images at build time to create a 'srcSet' for  '' or '' tags, or create versions in grayscale, duotone, cropped, rotated, etc.

When Gatsby builds from a Drupal source, it downloads the source images and processes them to create these image variations which are stored in the public directory. The ability to optimize and art-direct images at build time is great, but build performance suffers while these assets are generated. As a site grows in images, the time it takes to build grows as well. Image processing can take hours, while the rest of the build takes mere minutes.

Drupal has the built in ability to generate its own derivative images on demand and cache them, so why not just build our Gatsby components in a way that leverages Drupal Image Styles and dramatically speed up the Gatsby build process? Gatsby can just query for the image urls and let Drupal serve them directly.

For this experiment, I didn’t use Gatsby Image at all, though you could format your image data in a way that the Gatsby Image component expects, and still pass that in. My goal was to explore my options for getting image variants from Drupal via JSON:API and GraphQL, and to pass that to a custom React component, so that’s what I’ll demonstrate in this post.

I’ll show examples using both the core JSON:API module, as well as the GraphQL contrib module, which gives us a different developer experience.

Drupal Modules Used

Core: 
 - jsonapi
 - rest

Contrib:
 - graphql - An alternative to jsonapi with a developer experience that, so far, I prefer.
 - jsonapi_image_styles - required to access image styles with jsonapi, not required with graphql module.

Gatsby Configuration


{ 
  resolve: "gatsby-source-graphql", 
  options: { 
    typeName: "Drupal", 
    fieldName: "drupal", 
    url: `http://backend.lndo.site/graphql/` 
  }, 
}, 
{ 
  resolve: `gatsby-source-drupal`, 
  options: { 
    baseUrl: `http://backend.lndo.site/`, 
    apiBase: `jsonapi`, // optional, defaults to `jsonapi` 
    skipFileDownloads: true, 
  }, 
},

Here I’m configuring both the graphql and the drupal (jsonapi) sources. As this is only a local experiment, I’m not concerned with authentication and I’m using Lando/Docker for local development. In a real project, I’d extract the relevant parts to environment variables so they can be changed for the production server. I’d also only use one or the other, and not both.

In the graphql config, you’ll notice 'fieldName:' is set to 'drupal', which is what we’ll use to access the GraphQL API, as opposed to the JSON API.

In the 'gatsby-source-drupal' config I’ve set 'skipFileDownloads:' to 'true' because we will not need them for local processing or delivery. This skips all file downloads, but there are ways to be more specific using filters. https://www.gatsbyjs.com/plugins/gatsby-source-drupal/#filters

Option 1: GraphQL

Query Against the GraphQL API


query($id: String!) {
  drupal {
    nodeById(id: $id) {
      ... on Drupal_NodeArticle {
        title: entityLabel
        author: entityOwner {
          authorName: entityLabel
        }
        body {
          processed
        }
        fieldImage {
          alt
          xxl: derivative (style: XXL) {
            width
            url
          }
          xl: derivative (style: XL) {
            width
            url
          }
          large: derivative (style: LARGE) {
            width
            url
          }
          medium: derivative (style: MEDIUM) {
            width
            url
          }
          small: derivative (style: SMALL) {
            width
            url
          }
        }
      }
    }
  }
}


This query is for a specific article node in Drupal that contains a field named 'field_image'.  With the GraphQL module in Drupal, we have access to the 'derivative' function that allows us to query for the values of a specific image style.

In this case we’ve set up 5 image styles in Drupal which scale an image to different widths:

  • Small: 300
  • Medium: 600
  • Large: 1200
  • XL: 1800
  • XXL: 2400

The sizes are meant to cover a “full width” image at various breakpoints or screen resolutions.  Of course, you can set up Image Styles more suited to your needs.

We can alias each derivative by prefixing it with the style name and a colon, allowing us to have multiple derivatives in the same query, setting the style argument to the appropriate style name.

The result of the query includes all the values we need for our Image component.


        "fieldImage": {
          "alt": "Arduino",
          "xxl": {
            "width": 2400,
            "url": "http://backend.lndo.site/sites/default/files/styles/xxl/public/2020-09/arduino-harrison-broadbent_0.jpg?itok=EyvwD2ta"
          },
          "xl": {
            "width": 1800,
            "url": "http://backend.lndo.site/sites/default/files/styles/xl/public/2020-09/arduino-harrison-broadbent_0.jpg?itok=0gub18uQ"
          },
          "large": {
            "width": 1200,
            "url": "http://backend.lndo.site/sites/default/files/styles/large/public/2020-09/arduino-harrison-broadbent_0.jpg?itok=eNUhJHb6"
          },
          "medium": {
            "width": 600,
            "url": "http://backend.lndo.site/sites/default/files/styles/medium/public/2020-09/arduino-harrison-broadbent_0.jpg?itok=Rvsmw0an"
          },
          "small": {
            "width": 300,
            "url": "http://backend.lndo.site/sites/default/files/styles/small/public/2020-09/arduino-harrison-broadbent_0.jpg?itok=sNDME4Ju"
          }
        }

We can see that the url for each style is specific to the path Drupal will use to serve that version of the image. We’re letting Drupal do the work.

Next: An Article Component

Here we put it all together to render a node.


import React from 'react';
import { Link, graphql } from 'gatsby';
import Layout from '../components/layout';
import Image from '../components/image';

export const query = graphql`
query($id: String!) {
  drupal {
    nodeById(id: $id) {
      ... on Drupal_NodeArticle {
        title: entityLabel
        author: entityOwner {
          authorName: entityLabel
        }
        body {
          processed
        }
        fieldImage {
          alt
          xxl: derivative (style: XXL) {
            width
            url
          }
          xl: derivative (style: XL) {
            width
            url
          }
          large: derivative (style: LARGE) {
            width
            url
          }
          medium: derivative (style: MEDIUM) {
            width
            url
          }
          small: derivative (style: SMALL) {
            width
            url
          }
        }
      }
    }
  }
}`

const ArticleTemplate = ({ data: { drupal: { nodeById: article } }}) => {

  return (
    
      
        
        

Posted by {article.author.authorName}

                        ← Back  to all articles             ); }; export default ArticleTemplate;

This 'fieldImage' object is passed to the Image component as the first prop named 'image'. Our second prop is named 'sizes' and this is set manually where we call our Image component. It gives us some control over which version of the image is rendered given what we know about how wide it will be in the layout at certain breakpoints.

Next: An Image Component

I want to create a responsive image with a 'srcSet' similar to what we would get with gatsby-image.


import React from 'react';

const Image = ({image, sizes}) => {

  const derivatives = [];

  for (const derivative in image) {
    if (image[derivative].url) {
      derivatives.push(`${image[derivative].url} ${image[derivative].width}w`);
    }
  }

  const srcSet = derivatives.join();

  return (
    {image.alt}
  );
};

export default Image;

The '' tag will need 'srcSet', 'sizes', 'src' and 'alt' values. The query to the GraphQL API in Drupal collects all this information, returning it in the 'fieldImage' object that we passed to the 'image' prop. The 'for' loop iterates over the derivatives and concatenates each image URL with its width, pushing each to an array to create a set. The array is later joined to create the full value of the 'srcSet' image attribute. 
The 'src' attribute can have a value of any of the derivative urls. In this case 'image.small.url'.

Finally, the 'alt' attribute comes as part of the query, at 'image.alt'.

Option 2: JSON:API Version 

If you’re more comfortable with, or more invested in using the JSON:API rather than the GraphQL module in Drupal, you can achieve the same results with the addition of the 'jsonapi_image_styles' module, which exposes the image styles to the JSON:API.

In this case the query would look more like this:


  query($id: String!) {
    nodePage(id: { eq: $id }) {
      title
      field_image {
        alt
      }
      relationships {
        uid {
          display_name
        }
        field_image {
          image_style_uri {
            small
            medium
            large
            xl
            xxl
          }
        }
      }
      body {
        processed
      }
    }
  }

However, the results are a bit unexpected.


        "field_image": {
          "image_style_uri": [
            {
              "small": null,
              "medium": null,
              "large": "http://backend.lndo.site/sites/default/files/styles/large/public/2020-09/engin-akyurt-girl-blond-hair-unsplash.jpg?itok=MrcdTwGV",
              "xl": null,
              "xxl": null
            },
            {
              "small": null,
              "medium": "http://backend.lndo.site/sites/default/files/styles/medium/public/2020-09/engin-akyurt-girl-blond-hair-unsplash.jpg?itok=vQx__izk",
              "large": null,
              "xl": null,
              "xxl": null
            },
            {
              "small": "http://backend.lndo.site/sites/default/files/styles/small/public/2020-09/engin-akyurt-girl-blond-hair-unsplash.jpg?itok=hKO4dR34",
              "medium": null,
              "large": null,
              "xl": null,
              "xxl": null
            },
            {
              "small": null,
              "medium": null,
              "large": null,
              "xl": "http://backend.lndo.site/sites/default/files/styles/xl/public/2020-09/engin-akyurt-girl-blond-hair-unsplash.jpg?itok=MPph1lH4",
              "xxl": null
            },
            {
              "small": null,
              "medium": null,
              "large": null,
              "xl": null,
              "xxl": "http://backend.lndo.site/sites/default/files/styles/xxl/public/2020-09/engin-akyurt-girl-blond-hair-unsplash.jpg?itok=sz-ymDam"
            }
          ]
        }
      },

We get an object for each image style that contains keys for all the image styles queried, with 'null' values, except for the style corresponding to that part of the query. I’m not sure why this is, but we have to process our results differently to build the 'srcSet'.  Let’s illustrate with a Picture component so we don’t have to change the Image component.


import React from 'react';

const Picture = ({image, alt, sizes}) => {

  const derivatives = [];
  let src = "";

  image.forEach(derivative => {
    if (derivative.small) {
      src = derivative.small
      derivatives.push(`${derivative.small} 300w`)
    }
    if (derivative.medium) {
      derivatives.push(`${derivative.medium} 600w`)
    }
    if (derivative.large) {
      derivatives.push(`${derivative.large} 1200w`)
    }
    if (derivative.xl) {
      derivatives.push(`${derivative.xl} 1800w`)
    }
    if (derivative.xxl) {
      derivatives.push(`${derivative.xxl} 2400w`)
    }
  })

  const srcSet = derivatives.join();

  return (
    
      
      {alt}
    
  );
};

export default Picture;

Notice that we also have an 'alt' prop because the 'alt' data comes from a different part of the query. It can’t be accessed from 'relationships.field_image' like the image styles are. 

Conclusion

Whichever API type you use on the backend, I hope I’ve shown that we can still leverage the power of Drupal to process images as they’re needed instead of having to download and process them during the Gatsby build, bloating the build time and the size of the build artifact. 

Combine this with the 'image_effects' module in Drupal and create image styles to meet many different needs. You can have your fast Gatsby build times and responsive images too!
 

"Code like nobody is watching... but then refactor. ;)"

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web