Skip to content

Rewrite README to explain how to add Gatsby image support to Cloudinary image data sourced from Sanity CMS #246

@olavea

Description

@olavea

As stated in issue #214, gatsby-transformer-cloudinary does not work with the Sanity Cloudinary Plugin. Not out of the box.

So the README needs a new main headin called "Add Gatsby Image Support to Cloudinary image data sourced from a CMS"

Sanity creates nodes with fields of type SanityCloudinaryAsset when you pick an image from Cloudinary. Unfortunately it does not have the shape require by gatsby-transformer-cloudinary.

To get around that you may create nodes with the correct shape.

Let say we have the Gatsby node of type SanityArticle with a field cover of type SanityCloudinaryAsset

// File: gatsby-node.js

exports.onCreateNode = async (gatsbyUtils) => {
  const { node, actions, createNodeId, createContentDigest } = gatsbyUtils
  const { createNode } = actions

  if (node.internal.type === "SanityArticle") {
    // Create the correct data shape
    const cloudinaryAssetData = {
      cloudName: "cloud-name", // use your cloudName
      publicId: node.cover.public_id,
      originalHeight: node.cover.height,
      originalWidth: node.cover.width,
      originalFormat: node.cover.format,
    }

    // Create a Gatsby node with the correct data shape
    createNode({
      ...cloudinaryAssetData,
      id: createNodeId(`SanityCloudinaryAsset >>> ${node.cover.public_id}`),
      parent: node.id,
      internal: {
        type: "CloudinaryAsset", // or another type, remember to define `transformTypes` if you use another type
        contentDigest: createContentDigest(cloudinaryAssetData),
      },
    })
  }
}

exports.createSchemaCustomization = async ({ actions }) => {
  // Update the schema to add a link to the node with the correct shape
  actions.createTypes(/* GraphQL */ `
    type SanityArticle implements Node {
      coverImage: CloudinaryAsset
        @link(by: "publicId", from: "cover.public_id")
    }
 `)
}

You may now query for the gatsbyImageData on coverImage:

allSanityHomepageHero {
    nodes {
      coverImage {
        gatsbyImageData(height: 300)
      }
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    documentationImprovements or additions to documentation

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions