question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[gatsby-source-graphql] No localFile on featuredImage from Wordpress

See original GitHub issue

What’s the current situation with gatsby-image and querying it through gatsby-source-graphql. With REST API and gatsby-source-wordpress the query looked like this:

featured_media {
  alt_text
  localFile {
    childImageSharp {
      fluid(maxWidth: 1200, maxHeight: 600, cropFocus: CENTER, quality: 100) {
        ...GatsbyImageSharpFluid
        srcSet
      }
    }
  }
}

The localFile or imageSharp is no where to find on the featured_media when used along side gatsby-source-graphql.

Is this on gatsby-source-graphql’s end or does it have to do with some of the external plugins as such as gatsby-plugin-sharp?

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:10 (4 by maintainers)

github_iconTop GitHub Comments

3reactions
omattmancommented, Apr 1, 2020

Hi @fabianderijk, the workaround was to use the gatsby-source-filesystem in combination with your gatsby-source-graphql package to fetch and create a media type that allows the usage of featuredImage. Below is the packages I included in my gatsby-config file:

{
  resolve: `gatsby-source-filesystem`,
  options: {
    path: path.resolve(`./src`) // this should be your folder containing project files
  }
},
{
  resolve: "gatsby-source-graphql",
  options: {
    typeName: "WP",
    fieldName: "wp", // the query name
    url: "INSERT_YOUR_GRAPHQL_ENDPOINT"
  }
},

And in my gatsby-node file I would then fetch the remote files and create nodes that would allow me to use ImageSharp:

const { createRemoteFileNode } = require(`gatsby-source-filesystem`);

exports.createResolvers = ({
  actions,
  cache,
  createNodeId,
  createResolvers,
  store,
  reporter
}) => {
  const { createNode } = actions;
  createResolvers({
    WP_MediaItem: {
      imageFile: {
        type: `File`,
        resolve(source, args, context, info) {
          return createRemoteFileNode({
            url: source.sourceUrl,
            store,
            cache,
            createNode,
            createNodeId,
            reporter
          });
        }
      }
    }
  });
};

The above would create a query type imageFile on WP_MediaItem, which allows you to query for ImageSharp. An example of this is seen below:

export const query = graphql`
  query PageQuery($uri: String) {
    wp { // remember this from the query name in gatsby-source-graphql?
      pageBy(uri: $uri) {
        featuredImage {
          sourceUrl
          altText
          imageFile { // this is the node we created in gatsby-node
            childImageSharp {
              fluid(
                maxWidth: 2000
                maxHeight: 1000
                cropFocus: ATTENTION
                grayscale: true
              ) {
                ...GatsbyImageSharpFluid_withWebp
                srcSet
              }
            }
          }
        }
      }
    }
  }
`;

Hope this clarified the issue. If not, feel free to reach out 👍.

1reaction
omattmancommented, Sep 14, 2020

Hi @h0rhay and @antoinerousseau. Sorry I haven’t been able to reach out sooner.

Things have changed in both Gatsby and the GraphQL plugin which made my previous answer redundant. In particular there’s changes to how we query the featuredImage and how the resolver is structured.

Remark: my resolver handles issues with non-english letters being escaped by encodeURI. If this isn’t needed in your case you can omit the selective statement and encode function.

Start by updating the resolver in gatsby-node.js:

exports.createResolvers = async ({
  actions,
  cache,
  createNodeId,
  createResolvers,
  store,
  reporter,
}) => {
  const { createNode } = actions;

  await createResolvers({
    WP_MediaItem: {
      imageFile: {
        type: `File`,
        async resolve(source) {
          let sourceUrl = source.sourceUrl;

          if (source.mediaItemUrl !== undefined) {
            sourceUrl = source.mediaItemUrl;
          }

          return await createRemoteFileNode({
            url: encodeURI(sourceUrl), // if encoding is unnecessary just replace with source.sourceUrl
            store,
            cache,
            createNode,
            createNodeId,
            reporter,
          });
        },
      },
    },
  });
};

For the query we now have to care about the new structure of featuredImage. Every featuredImage node contains a nested node structure, which was absent from my previous example:

export const query = graphql`
  query ArtistProfileQuery($id: ID!) {
    wp {
      artist(id: $id) {
        featuredImage {
          node { // THIS IS THE NEW NESTED NODE STRUCTURE
            sourceUrl
            altText
            imageFile {
              childImageSharp {
                fluid(
                  maxWidth: 2000
                  maxHeight: 1000
                  cropFocus: ATTENTION
                  grayscale: true
                ) {
                  ...GatsbyImageSharpFluid_withWebp
                  srcSet
                }
              }
            }
          }
        }
      }
    }
  }
`;

This also means that any previous references to for example data.wp.featuredImage.imageFile.childImageSharp.fluid should be changed to contain the node so that it becomes data.wp.featuredImage.node.imageFile.childImageSharp.fluid. The references might contain a data prefix as in my example, but depends on your particular setup.

I hope this was of any assistance to you both. If that was not the case do not hesitate to reach out once again.

Read more comments on GitHub >

github_iconTop Results From Across the Web

GatsbyImage not working in production site (Pulling data ...
I'm using Wordpress CMS to set featured images to posts, and trying to render those images in Gatsby. So far, it works when...
Read more >
How to handle Images and make use of gatsby-image
We gonna make use of Gatsby's abilities to add custom resolvers, to customize the schema, so that WordPress images get handled as local...
Read more >
Adding Images to a WordPress Site
What this tutorial covers: Why go through this tutorial? Installing the gatsby-source-wordpress plugin; Installing plugins to help with images; Creating GraphQL ...
Read more >
gatsby-source-graphql
Gatsby plugin which adds a third-party GraphQL API to Gatsby GraphQL. Latest version: 5.3.1, last published: 9 days ago.
Read more >
Creating a Gatsby Site with WordPress Data
Unlike WordPress, newer WPGraphQL releases do not support ... Next, we're going to install and configure the gatsby-source-graphql plugin.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found