gatsby-source-sanity icon indicating copy to clipboard operation
gatsby-source-sanity copied to clipboard

Resolve Gatsby image data in `_rawContent`

Open aaronadamsCA opened this issue 3 years ago • 4 comments
trafficstars

I'd like to see a new option in the GraphQL schema to resolve Gatsby image data in _rawContent.

Intended usage:

{
  allSanityPage {
    nodes {
      id
      _rawContent(
        resolveReferences: {maxDepth: 10}
        resolveGatsbyImageData: {width: 1600}
      )
    }
  }
}

Intended result: Block content objects of "_type": "image" would contain asset.gatsbyImageData. This could be passed directly to gatsby-plugin-image while serializing block content, for example:

import { GatsbyImage } from "gatsby-plugin-image";

export const imageSerializer = ({ node }) => {
  return <GatsbyImage image={node.asset.gatsbyImageData} />;
};

This would make life with block content and Gatsby a lot easier!

aaronadamsCA avatar Jan 07 '22 23:01 aaronadamsCA

My amusing workaround, for now, is to populate siteMetadata with my Sanity projectId and dataset, and then use this very clumsy image serializer:

import { graphql, StaticQuery } from "gatsby";
import { GatsbyImage } from "gatsby-plugin-image";
import { getGatsbyImageData } from "gatsby-source-sanity";

export const imageSerializer = ({ node: { asset } }) => (
  <StaticQuery
    query={graphql`
      {
        site {
          siteMetadata {
            sanityLocation {
              projectId
              dataset
            }
          }
        }
      }
    `}
    render={({ site: { siteMetadata } }) => (
      <GatsbyImage
        image={getGatsbyImageData(asset._id, {}, siteMetadata.sanityLocation)}
      />
    )}
  />
);

aaronadamsCA avatar Jan 07 '22 23:01 aaronadamsCA

Is this the only way to do this?

1-800-jono avatar Aug 17 '22 20:08 1-800-jono

As far as I know.

I mean - there are for sure better ways to grab projectId and dataset. For us, we'll probably switch to a context-based solution for that part when we eventually refactor that code.

But resolving the image data still needs to be done in the serializer, and is not happening inside the Gatsby graph.

aaronadamsCA avatar Aug 18 '22 16:08 aaronadamsCA

Thanks @aaronadamsCA - I was able to solve the issue with your comment.

1-800-jono avatar Aug 18 '22 16:08 1-800-jono