Giter Site home page Giter Site logo

sanity-io / gatsby-source-sanity Goto Github PK

View Code? Open in Web Editor NEW
197.0 20.0 61.0 9.67 MB

Gatsby source plugin for building websites using Sanity.io as a backend.

Home Page: https://www.sanity.io/

License: MIT License

JavaScript 0.51% TypeScript 99.49%
sanity gatsby real-time preview gatsby-source-sanity gatsby-image team-ecosystem

gatsby-source-sanity's Introduction

gatsby-source-sanity

Gatsby source plugin for pulling data from Sanity.io into Gatsby websites. Develop with real-time preview of all content changes. Compatible with gatsby-plugin-image. Uses your project's GraphQL schema definitions to avoid accidental missing fields (no dummy-content needed).

Get up and running in minutes with a fully configured starter project:

Watch a video about the company website built with Gatsby using Sanity.io as a headless CMS

Table of contents

See the getting started video

Install

From the command line, use npm (node package manager) to install the plugin:

npm install gatsby-source-sanity gatsby-plugin-image

⚠️ Warning: If using Gatsby v4, make sure you've installed version 7.1.0 or higher. The plugin has a dependency on gatsby-plugin-image which itself has dependencies. Check gatsby-plugin-image README for instructions.

In the gatsby-config.js file in the Gatsby project's root directory, add the plugin configuration inside of the plugins section:

module.exports = {
  // ...
  plugins: [
    {
      resolve: `gatsby-source-sanity`,
      options: {
        projectId: `abc123`,
        dataset: `blog`,
        // a token with read permissions is required
        // if you have a private dataset
        token: process.env.SANITY_TOKEN,

        // If the Sanity GraphQL API was deployed using `--tag <name>`,
        // use `graphqlTag` to specify the tag name. Defaults to `default`.
        graphqlTag: 'default',
      },
    },
    `gatsby-plugin-image`,
    // ...
  ],
  // ...
}

You can access projectId and dataset by executing sanity debug --secrets in the Sanity studio folder. Note that the token printed may be used for development, but is tied to your Sanity CLI login session using your personal Sanity account - make sure to keep it secure and not include it in version control! For production, you'll want to make sure you use a read token generate in the Sanity management interface.

Basic usage

At this point you should set up a GraphQL API for your Sanity dataset, if you have not done so already. This will help the plugin in knowing which types and fields exists, so you can query for them even without them being present in any current documents.

You should redeploy the GraphQL API everytime you make changes to the schema that you want to use in Gatsby by running sanity graphql deploy from within your Sanity project directory

Explore http://localhost:8000/___graphql after running gatsby develop to understand the created data and create a new query and checking available collections and fields by typing Ctrl + Space.

Options

Options Type Default Description
projectId string [required] Your Sanity project's ID
dataset string [required] The dataset to fetch from
token string Authentication token for fetching data from private datasets, or when using overlayDrafts Learn more
graphqlTag string default If the Sanity GraphQL API was deployed using --tag <name>, use this to specify the tag name.
overlayDrafts boolean false Set to true in order for drafts to replace their published version. By default, drafts will be skipped.
watchMode boolean false Set to true to keep a listener open and update with the latest changes in realtime. If you add a token you will get all content updates down to each key press.
watchModeBuffer number 150 How many milliseconds to wait on watchMode changes before applying them to Gatsby's GraphQL layer. Introduced in 7.2.0.
typePrefix string Prefix to use for the GraphQL types. This is prepended to Sanity in the type names and allows you to have multiple instances of the plugin in your Gatsby project.

Preview of unpublished content

Sometimes you might be working on some new content that is not yet published, which you want to make sure looks alright within your Gatsby site. By setting the overlayDrafts setting to true, the draft versions will as the option says "overlay" the regular document. In terms of Gatsby nodes, it will replace the published document with the draft.

Keep in mind that drafts do not have to conform to any validation rules, so your frontend will usually want to double-check all nested properties before attempting to use them.

GraphQL API

By deploying a GraphQL API for your dataset, we are able to introspect and figure out which schema types and fields are available and make informed choices based on this information.

Previous versions did not require this, but often lead to very confusing and unpredictable behavior, which is why we have now made it a requirement.

Using images

Image fields will have the image URL available under the field.asset.url key, but you can also use gatsby-plugin-image for a smooth experience. It's a React component that enables responsive images and advanced image loading techniques. It works great with this source plugin, without requiring any additional build steps.

import React from 'react'
import {GatsbyImage} from 'gatsby-plugin-image'

const sanityConfig = {projectId: 'abc123', dataset: 'blog'}

const Person = ({data}) => {
  return (
    <article>
      <h2>{data.sanityPerson.name}</h2>
      <GatsbyImage image={data.sanityPerson.profileImage.asset.gatsbyImageData} />
    </article>
  )
}

export default Person

export const query = graphql`
  query PersonQuery {
    sanityPerson {
      name
      profileImage {
        asset {
          gatsbyImageData(fit: FILLMAX, placeholder: BLURRED)
        }
      }
    }
  }
`

Note: we currently don't support the format option of gatsbyImageData. Our image CDN automatically serves the best format for the user depending on their device, so you don't need to define formats manually.

Using Gatsby's Image CDN (beta)

This plugin supports Gatsby's new Image CDN feature. To use it, follow the instructions in the section above, but substitute the gatsbyImageData field for gatsbyImage.

Using images outside of GraphQL

If you are using the raw fields, or simply have an image asset ID you would like to use gatsby-plugin-image for, you can import and call the utility function getGatsbyImageData

import {GatsbyImage} from 'gatsby-plugin-image'
import {getGatsbyImageData} from 'gatsby-source-sanity'

const sanityConfig = {projectId: 'abc123', dataset: 'blog'}
const imageAssetId = 'image-488e172a7283400a57e57ffa5762ac3bd837b2ee-4240x2832-jpg'

const imageData = getGatsbyImageData(imageAssetId, {maxWidth: 1024}, sanityConfig)

<GatsbyImage image={imageData} />

Generating pages

Sanity does not have any concept of a "page", since it's built to be totally agnostic to how you want to present your content and in which medium, but since you're using Gatsby, you'll probably want some pages!

As with any Gatsby site, you'll want to create a gatsby-node.js in the root of your Gatsby site repository (if it doesn't already exist), and declare a createPages function. Within it, you'll use GraphQL to query for the data you need to build the pages.

For instance, if you have a project document type in Sanity that you want to generate pages for, you could do something along the lines of this:

exports.createPages = async ({graphql, actions}) => {
  const {createPage} = actions

  const result = await graphql(`
    {
      allSanityProject(filter: {slug: {current: {ne: null}}}) {
        edges {
          node {
            title
            description
            tags
            launchDate(format: "DD.MM.YYYY")
            slug {
              current
            }
            image {
              asset {
                url
              }
            }
          }
        }
      }
    }
  `)

  if (result.errors) {
    throw result.errors
  }

  const projects = result.data.allSanityProject.edges || []
  projects.forEach((edge, index) => {
    const path = `/project/${edge.node.slug.current}`

    createPage({
      path,
      component: require.resolve('./src/templates/project.js'),
      context: {slug: edge.node.slug.current},
    })
  })
}

The above query will fetch all projects that have a slug.current field set, and generate pages for them, available as /project/<project-slug>. It will use the template defined in src/templates/project.js as the basis for these pages.

Checkout Creating Pages from Data Programmatically to learn more.

Remember to use the GraphiQL interface to help write the queries you need - it's usually running at http://localhost:8000/___graphql while running gatsby develop.

"Raw" fields

Arrays and object types at the root of documents will get an additional "raw JSON" representation in a field called _raw<FieldName>. For instance, a field named body will be mapped to _rawBody. It's important to note that this is only done for top-level nodes (documents).

Quite often, you'll want to replace reference fields (eg _ref: '<documentId>'), with the actual document that is referenced. This is done automatically for regular fields, but within raw fields, you have to explicitly enable this behavior, by using the field-level resolveReferences argument:

{
  allSanityProject {
    edges {
      node {
        _rawTasks(resolveReferences: {maxDepth: 5})
      }
    }
  }
}

Portable Text / Block Content

Rich text in Sanity is usually represented as Portable Text (previously known as "Block Content").

These data structures can be deep and a chore to query (specifying all the possible fields). As noted above, there is a "raw" alternative available for these fields which is usually what you'll want to use.

You can install @portabletext/react from npm and use it in your Gatsby project to serialize Portable Text. It lets you use your own React components to override defaults and render custom content types. Learn more about Portable Text in our documentation.

Using multiple datasets

If you want to use more than one dataset in your site, you can do so by adding multiple instances of the plugin to your gatsby-config.js file. To avoid conflicting type names you can use the typeName option to set a custom prefix for the GraphQL types. These can be datasets from different projects, or different datasets within the same project.

// In your gatsby-config.js
module.exports = {
  plugins: [
    {
      resolve: 'gatsby-source-sanity',
      options: {
        projectId: 'abc123',
        dataset: 'production',
      },
    },
    {
      resolve: 'gatsby-source-sanity',
      options: {
        projectId: 'abc123',
        dataset: 'staging',
        typePrefix: 'Staging',
      },
    },
  ],
}

In this case, the type names for the first instance will be Sanity<typeName>, while the second will be StagingSanity<typeName>.

Real-time content preview with watch mode

While developing, it can often be beneficial to get updates without having to manually restart the build process. By setting watchMode to true, this plugin will set up a listener which watches for changes. When it detects a change, the document in question is updated in real-time and will be reflected immediately.

If you add a token with read rights and set overlayDrafts to true, each small change to the draft will immediately be applied. Keep in mind that this is mainly intended for development, see next section for how to enable previews for your entire team.

Updating content for editors with preview servers

You can use Gatsby preview servers (often through Gatsby Cloud) to update your content on a live URL your team can use.

In order to have previews working, you'll need to activate overlayDrafts in the plugin's configuration inside preview environments. To do so, we recommend following a pattern similar to this:

// In gatsby-config.js

const isProd = process.env.NODE_ENV === "production"
const previewEnabled = (process.env.GATSBY_IS_PREVIEW || "false").toLowerCase() === "true"

module.exports = {
  // ...
  plugins: [
    resolve: "gatsby-source-sanity",
    options: {
      // ...
      watchMode: !isProd, // watchMode only in dev mode
      overlayDrafts: !isProd || previewEnabled, // drafts in dev & Gatsby Cloud Preview
    },
  ]
}

Then, you'll need to set-up a Sanity webhook pointing to your Gatsby preview URL. Create your webhook from this template, making sure you update the URL.

If using Gatsby Cloud, this should be auto-configured during your initial set-up.

⚠️ Warning: if you have Gatsby Cloud previews v1 enabled on your site, you'll need to reach out to their support for enabling an upgrade. The method described here only works with the newer "Incremental CMS Preview", webhook-based system.


You can also follow the manual steps below:

  1. Get the webhook endpoint needed for triggering Gatsby Cloud previews in their dashboard.

  2. Go to sanity.io/manage and navigate to your project

  3. Under the "API" tab, scroll to Webhooks or "GROQ-powered webhooks"

  4. Add a new webhook and name it as you see fit

  5. Choose the appropriate dataset and add the Gatsby Cloud webhook endpoint to the URL field

  6. Keep the HTTP method set to POST, skip "HTTP Headers"

  7. Set the hook to trigger on Create, Update and Delete

  8. Skip the filter field

  9. Specify the following projection:

    select(delta::operation() == "delete" => {
      "operation": delta::operation(),
      "documentId": coalesce(before()._id, after()._id),
      "projectId": sanity::projectId(),
      "dataset": sanity::dataset(),
    }, {})
  10. Set the API version to v2021-03-25

  11. And set it to fire on drafts

  12. Save the webhook

Using .env variables

If you don't want to attach your Sanity project's ID to the repo, you can easily store it in .env files by doing the following:

// In your .env file
SANITY_PROJECT_ID = abc123
SANITY_DATASET = production
SANITY_TOKEN = my_super_secret_token

// In your gatsby-config.js file
require('dotenv').config({
  path: `.env.${process.env.NODE_ENV}`,
})

module.exports = {
  // ...
  plugins: [
    {
      resolve: 'gatsby-source-sanity',
      options: {
        projectId: process.env.SANITY_PROJECT_ID,
        dataset: process.env.SANITY_DATASET,
        token: process.env.SANITY_TOKEN,
        // ...
      },
    },
  ],
  // ...
}

This example is based off Gatsby Docs' implementation.

How this source plugin works

When starting Gatsby in development or building a website, the source plugin will first fetch the GraphQL Schema Definitions from a Sanity deployed GraphQL API. The source plugin uses this to tell Gatsby which fields should be available to prevent it from breaking if the content for certain fields happens to disappear. Then it will hit the project’s export endpoint, which streams all the accessible documents to Gatsby’s in-memory datastore.

In other words, the whole site is built with two requests. Running the development server, will also set up a listener that pushes whatever changes come from Sanity to Gatsby in real-time, without doing additional API queries. If you give the source plugin a token with permission to read drafts, you’ll see the changes instantly.

Credits

Huge thanks to Henrique Doro for doing the initial implementation of this plugin, and for donating it to the Sanity team. Mad props!

Big thanks to the good people backing Gatsby for bringing such a joy to our developer days!

Develop

Release new version

Run "CI & Release" workflow. Make sure to select the main branch and check "Release new version".

Semantic release will only release on configured branches, so it is safe to run release on any branch.

gatsby-source-sanity's People

Contributors

ascorbic avatar atombender avatar augustskare avatar ax-vasquez avatar bjoerge avatar chrispecoraro avatar d4v1d82 avatar evenwestvang avatar github-actions[bot] avatar hdoro avatar kathmbeck avatar kbrabrand avatar kmelve avatar lekoarts avatar mattmischuk avatar mshick avatar paalfredrik avatar pierrenel avatar renovate[bot] avatar rexxars avatar rick-flores avatar ricokahler avatar runeb avatar ryami333 avatar semantic-release-bot avatar stipsan avatar tyhopp avatar tylerbarnes avatar wesbos avatar yago avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

gatsby-source-sanity's Issues

Gatsby v3 doesn't like @dontinfer

When i build gatsby 2.15.29 it says:

warn On types with the `@dontInfer` directive, or with the `infer` extension set to `false`, automatically adding fields for children types is deprecated.
In Gatsby v3, only children fields explicitly set with the `childOf` extension will be added.
For example, in Gatsby v3, `SanityImageAsset` will not get a `childImageSharp` field.

Axios version security warning

Github's automated security alert has flagged a warning for axios version 0.18.0 - CVE-2019-10742

I upgraded the verison to 0.19.0 locally and it passed Jest testing. I haven't had a chance to test it when integrated into a Gatsby site though

Images are getting cropped unexpectedly

I’m working on integrating a Gatsby site with Sanity. I previously had all data as local files (markdown/images) and the images were loaded with gatsby-image-sharp. The change to fetch the content from Sanity with the gatsby-source-sanity plugin has been mostly smooth but with one major issue. When querying images with a fixed height or fluid maxHeight the images is returned cropped. I want the original aspect ratio but with the images scaled to the desired height and I had this working with the old setup with local images.

An example of what the relevant part of a query looked like before:

image {
	childImageSharp {
		fixed(height: 140) {
			…GatsbyImageSharpFixed
		}
	}
}

And now with Sanity to:

image {
	asset {
		fixed(height: 140) {
			…GatsbySanityImageFixed
		}
	}
}

What I found when digging a bit deeper was that this plugin adds &fit=crop to the image url from sanity cdn. If I manually remove this url-parameter in the dev tools I get the image I want that is the original aspect ratio and 140px in height in this example.

Based on a discussion in the Sanity slack this does not seem to be expected behavior. Maybe this can be solved by adding a crop boolean parameter to the graphql schema to make the cropping optional?

[bug] allSanityPost returns null when post is edited during live preview

When I do a live edit of an existing post, a page that queries an allSanityPost query becomes undefined.

A screenshot of the console before and after the edit
Screen Shot 2020-04-28 at 6 52 42 PM

{
  "private": false,
  "name": "hungrygatsbydev-frontend",
  "version": "1.0.0",
  "author": "Sanity <[email protected]>",
  "engines": {
    "node": "10.x"
  },
  "scripts": {
    "build": "gatsby build",
    "deploy": "npm run now-deploy",
    "develop": "gatsby develop",
    "empty-cache": "gatsby clean",
    "lint": "eslint .",
    "now-build": "npm run build",
    "now-dev": "npm run build",
    "start": "npm run develop",
    "format": "prettier-eslint --write \"**/*.js\" \"!.cache/**\" \"!node_modules/**\" \"!public/**\"",
    "test": "echo \"Write tests! -> https://gatsby.app/unit-testing\""
  },
  "dependencies": {
    "@babel/core": "^7.9.0",
    "@babel/plugin-proposal-optional-chaining": "^7.9.0",
    "@bumped-inc/gatsby-plugin-optional-chaining": "^1.0.0",
    "@sanity/block-content-to-react": "^2.0.7",
    "@sanity/image-url": "^0.140.18",
    "@theme-ui/presets": "^0.3.0",
    "date-fns": "^1.30.1",
    "deepmerge": "^4.2.2",
    "dotenv": "^8.2.0",
    "gatsby": "^2.20.18",
    "gatsby-image": "^2.3.2",
    "gatsby-plugin-next-seo": "^1.4.0",
    "gatsby-plugin-react-helmet": "^3.2.2",
    "gatsby-plugin-robots-txt": "^1.5.0",
    "gatsby-plugin-sitemap": "^2.4.0",
    "gatsby-plugin-theme-ui": "^0.3.0",
    "gatsby-source-sanity": "^5.0.6",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-helmet": "^5.2.1",
    "react-helmet-async": "^1.0.5",
    "react-icons": "^3.10.0",
    "react-photo-gallery": "^8.0.0",
    "react-toggle": "^4.1.1",
    "theme-ui": "^0.3.1"
  },
  "devDependencies": {
    "eslint": "^6.8.0",
    "eslint-config-standard": "^14.1.1",
    "eslint-config-standard-react": "^9.2.0",
    "eslint-plugin-import": "^2.20.2",
    "eslint-plugin-node": "^10.0.0",
    "eslint-plugin-promise": "^4.2.1",
    "eslint-plugin-react": "^7.19.0",
    "eslint-plugin-standard": "^4.0.1",
    "prettier-eslint-cli": "^5.0.0",
    "prop-types": "^15.7.2"
  }
}

sample query

query {
posts: allSanityPost(limit: 6, sort: { fields: [publishedAt], order: DESC }) {
      edges {
        node {
          id
          publishedAt
          path
          mainImage {
            crop {
              _key
              _type
              top
              bottom
              left
              right
            }
            hotspot {
              _key
              _type
              x
              y
              height
              width
            }
            asset {
              _id
              fluid(maxWidth: 600, maxHeight: 400) {
                ...GatsbySanityImageFluid_noBase64
              }
            }
            alt
          }
          title
          excerpt
          slug {
            current
          }
        }
      }
    }
  }
}

gatsby-config.js

require('dotenv').config()
const {
  api: { projectId, dataset }
} = requireConfig('../studio/sanity.json')

const activeEnv = process.env.GATSBY_ACTIVE_ENV || process.env.NODE_ENV || 'development'

console.log(activeEnv)

module.exports = {
  plugins: [
    '@bumped-inc/gatsby-plugin-optional-chaining',
    'gatsby-plugin-react-helmet',
    'gatsby-plugin-theme-ui',
    {
      resolve: 'gatsby-plugin-next-seo',
    },
    {
      resolve: 'gatsby-source-sanity',
      options: {
        projectId,
        dataset,
        // To enable preview of drafts, copy .env-example into .env,
        // and add a token with read permissions
        token: process.env.SANITY_TOKEN,
        watchMode: activeEnv === 'development',
        overlayDrafts: true
      }
    },
    {
      resolve: 'gatsby-plugin-sitemap',
      options: {
        query: `
          {
            sanitySiteSettings {
              url
            }
            allSitePage {
              nodes {
                path
              }
            }
        }`,
        resolveSiteUrl: ({ sanitySiteSettings }) => {
          // Alternativly, you may also pass in an environment variable (or any location) at the beginning of your `gatsby-config.js`.
          return sanitySiteSettings.url
        }
      }
    },
    {
      resolve: 'gatsby-plugin-robots-txt',
      options: {
        policy: [{ userAgent: '*', allow: '/' }]
      }
    }
  ]
}

/**
 * We're requiring a file in the studio folder to make the monorepo
 * work "out-of-the-box". Sometimes you would to run this web frontend
 * in isolation (e.g. on codesandbox). This will give you an error message
 * with directions to enter the info manually or in the environment.
 */

function requireConfig (path) {
  try {
    return require('../studio/sanity.json')
  } catch (e) {
    console.error(
      'Failed to require sanity.json. Fill in projectId and dataset name manually in gatsby-config.js'
    )
    return {
      api: {
        projectId: process.env.SANITY_PROJECT_ID || '',
        dataset: process.env.SANITY_DATASET || ''
      }
    }
  }
}

Release notes

Is there a way to track changes that are made/improved with new releases? I'm currently using 1.0.4 but would love to know what improvements have been made?

Types are incompatible with gatsby-image

I'm trying to use the fragment GatsbySanityImageFixed for my images in my graphql query and i use gatsby-plugin-graphql-codegen plugin to generate these types .But the FixedImage type on gatsby-image seems to be incompatible with the one's returned by GatsbySanityImageFixed. There's all the null and undefined in the object properties like width, height etc which makes them incompatible. Any workaround to this? How do i get this to work with Typescript?

This is my code -

import Img from 'gatsby-image';

interface Props {
  data: AnotherGreatQueryNameQuery;
}

const Test = ({ data }: Props) => {
  return (
    <Layout>
      <Img fixed={data.sanityPortfolio?.profilePhoto?.asset?.fixed!} />
    </Layout>
  );
};

export const query = graphql`
  query AnotherGreatQueryName {
    sanityPortfolio(slug: { current: { eq: "portfolio" } }) {
      profilePhoto {
        asset {
          fixed(width: 150, height: 150) {
            ...GatsbySanityImageFixed
          }
        }
      }
    }
  }
`;

This is the error typescript throws -

Type 'Pick<SanityImageFixed, "height" | "width" | "src" | "srcSet" | "base64" | "srcWebp" | "srcSetWebp">' is not assignable to type 'FixedObject'

Thanks in advance!

[6.0.0-beta.0] markDefs not available on GraphQL

I was testing the new version today which fixes the terribly annoying nested blocks bug (and thank you very much for that 😄), but while testing whether I could now just avoid using _raw fields and get all fields manually I noticed there's still a missing field, which is markDefs.

In the screenshot below you can see I managed to grab all fields that I needed to make body the same as _rawBody, except for markDefs.

printScreen

References in block arrays

Just played with the new version (v1), which is very nice, but the trick I used here doesn't work anymore. I am opening a new ticket, since it is strictly speaking a separate issue.

It is this: If my block has a reference to another object, it isn't included in fooRaw. Which I recognize is a problem - who knows how many levels deep I might want to follow. Using the old system, I could use a syntax trick in the way I define my own types in the Gatsby plugin to get the resolved reference.

I wonder what can be done here?

Use arguments?

textRaw(followRefs: {depth: 3})

Allow me to query directly? As long as all the fields are always available (e.g. markDef) could this possibly work? Using a fragment to query all the fields of a block necessary for render would be quite usuable, DX-wise.

This has the added advantage of allowing me to not query certain fields of my own types that are included in a block content array: Fields that might contain private information, for example, which I do not want to be exposed. Thinking about how Gatsby works - AFAIK it exports and loads the GraphQL Query result for each page on navigation, thus making it public in full - hiding private information is not something that can be done with textRaw.

I also notice something else interesting going on. Given the following schema:

{
      title: 'Text',
      name: 'text',
      type: 'array',
      of: [
        {
          type: 'block',
          of: []
        },
        {type: 'quote'},
        {type: 'galleryWithText'},
        {type: 'reference', to: {type: 'keyPoint'}},
      ]
}

As long as I only use the quote and galleryWithText types, a query for

children {
  id,
  __typename
},
text {
  _key
  _type            
}

has this response:

{
             children": [],
            "text": [
              {
                "_key": "c0eea66c0a54",
                "_type": "block"
              },
              {
                "_key": "12c6882e9317",
                "_type": "galleryWithText"
              }
            ]
}

But as soon as I add the reference type in the studio, the result becomes:

{
            "children": [
              {
                "id": "...",
                "__typename": "SanityBlock"
              },
              {
                "id": "...",
                "__typename": "SanityGalleryWithText"
              }
            ],
            "text": null
          }

For now I am going to remove the reference from the block array. It is not that important to me, and the UI in the studio isn't perfect either, but I do think it is worth supporting.

Gatsby build fails because of incompatible gatsby or gatsby-source-sanity version

I am running gatsby and sanity together. The structure of the project was constructed following this tutorial.

Now, the problem is that when I run the gatsby project, I get the following error:

You are running a version of Gatsby that is not supported by gatsby-source-sanity. Please downgrade to gatsby <= 2.1.22 or upgrade gatsby-source-sanity to >= 2.0.0.

My current dependencies are

"dependencies": {
    "@sanity/block-content-to-react": "^2.0.6",
    "@sanity/image-url": "^0.140.0",
    "date-fns": "^1.30.1",
    "dotenv": "^6.2.0",
    "gatsby": "^2.0.76",
    "gatsby-plugin-postcss": "^2.0.2",
    "gatsby-plugin-react-helmet": "^3.0.2",
    "gatsby-source-sanity": "^1.0.3",
    "postcss-import": "^12.0.1",
    "postcss-preset-env": "^6.5.0",
    "react": "^16.8.0",
    "react-dom": "^16.8.0",
    "react-helmet": "^5.2.0",
    "typeface-lato": "^0.0.54"
  },

Is it intentional that previously working build are now failing because of this?

Image in portable text with gatsby-image, low res images get upscaled instead of shown in original size.

I'm trying to display images added in portable text, but so far I've found problems with both getFluidGatsbyImage and getFixedGatsbyImage that prevent me from displaying them in a desirable way.

What I really want to achieve is to set a max width, for example 800px, for large images, but display images with a width lower than 800px at their original size.

However, both getFluidGatsbyImage and getFixedGatsbyImage seem to ignore the original width and render the image at maxWidth for fluid or 400px which is the default width for fixed.

Looking through the json that is returned from the _rawBody response I cannot even find any metadata that tells me what the original size of the image. If I had this I could at least limit the image container to that size to circumvent the issue.

Example of my image renderer:

import Image from "gatsby-image"
import { getFluidGatsbyImage } from "gatsby-source-sanity"
import React from "react"
import clientConfig from "../../client-config"

export function Figure({ node }) {
  const fluidProps = getFluidGatsbyImage(
    node.asset._id,
    { maxWidth: 800 },
    clientConfig.sanity
  )

  return (
    <figure>
      <Image fluid={fluidProps} alt={node.alt} />
      {node.caption && <figcaption>{node.caption}</figcaption>}
    </figure>
  )
}

@sanity giving following error: OutgoingMessage.prototype._headers is deprecated

When running gatsby develop I'm getting the following error:

 ERROR 

(node:89441) [DEP0066] DeprecationWarning: OutgoingMessage.prototype._headers is deprecated

running a node --trace-deprecation it seems to be coming from a sanity dependency:

(node:89499) [DEP0066] DeprecationWarning: OutgoingMessage.prototype._headers is deprecated
    at module.exports (/Users/ndimatteo/code/projects/new/the-fold/web/node_modules/timed-out/index.js:9:17)
    at module.exports (/Users/ndimatteo/code/projects/new/the-fold/web/node_modules/get-it/lib-node/request/node-request.js:146:5)
    at /Users/ndimatteo/code/projects/new/the-fold/web/node_modules/get-it/lib-node/index.js:48:24
    at Object.publish (/Users/ndimatteo/code/projects/new/the-fold/web/node_modules/nano-pubsub/index.js:18:22)
    at SanityObservableMinimal._subscribe (/Users/ndimatteo/code/projects/new/the-fold/web/node_modules/get-it/lib/middleware/observable.js:28:26)
    at SanityObservableMinimal.Observable._trySubscribe (/Users/ndimatteo/code/projects/new/the-fold/web/node_modules/rxjs/internal/Observable.js:44:25)
    at SanityObservableMinimal.Observable.subscribe (/Users/ndimatteo/code/projects/new/the-fold/web/node_modules/rxjs/internal/Observable.js:30:22)
    at FilterOperator.call (/Users/ndimatteo/code/projects/new/the-fold/web/node_modules/rxjs/internal/operators/filter.js:29:23)
    at SanityObservableMinimal.Observable.subscribe (/Users/ndimatteo/code/projects/new/the-fold/web/node_modules/rxjs/internal/Observable.js:25:31)
    at MapOperator.call (/Users/ndimatteo/code/projects/new/the-fold/web/node_modules/rxjs/internal/operators/map.js:32:23)
    at SanityObservableMinimal.Observable.subscribe (/Users/ndimatteo/code/projects/new/the-fold/web/node_modules/rxjs/internal/Observable.js:25:31)
    at /Users/ndimatteo/code/projects/new/the-fold/web/node_modules/rxjs/internal/Observable.js:99:19
    at new Promise (<anonymous>)
    at SanityObservableMinimal.Observable.toPromise (/Users/ndimatteo/code/projects/new/the-fold/web/node_modules/rxjs/internal/Observable.js:97:16)
    at toPromise (/Users/ndimatteo/code/projects/new/the-fold/web/node_modules/@sanity/client/lib/sanityClient.js:36:21)
    at SanityClient.request (/Users/ndimatteo/code/projects/new/the-fold/web/node_modules/@sanity/client/lib/sanityClient.js:104:34)

Here's some stats about my setup:

  • Node version: v12.13.1
  • Gatsby CLI version: 2.10.2
  • Gatsby version: 2.20.29
  • gatsby-source-sanity version: ^5.0.6

Any idea what this is and how to resolve? It only seems to pop up when using this plugin.

Always(?) include image fragments

We are currently checking for any image assets before adding image fragments, since they reference the image asset schema type and will break if it is not present. However, if using an introspected schema, the type is always present and could thus be added regardless. This would solve the issue where you start with an empty dataset and have to restart the development server once you've added an image asset for the fragments to be usable.

Group on fields in nested object structures doesn't seem to work

Let's say you want to group posts by tags.

types: [
    ...schemaTypes,
    {
      name: 'post',
      type: 'document',
      title: 'Post',
      fields: [
        {
          name: 'title',
          type: 'string',
          title: 'Title',
        },
        {
          name: 'tags',
          type: 'array',
          title: 'Tags',
          of: [
              { type: 'reference', to: [{type: 'tag'}]}
          ]
        },
      ]
    },
    {
      name: 'tag',
      type: 'document',
      title: 'Tag',
      fields: [
        {
          name: 'title',
          type: 'string',
          title: 'Title',
        },
      ]
    }
  ])

This results in either
image

or

image

Portable text / blocks not useful when used inside an array or object

When querying for a block that resides within another object i.e. not at root level there doesn't seem to be a way to get any useful information out of it.

Example query:

query MyQuery {
  sanityPage {
    modules {
      ... on SanityRichText {
        _key
        _type
        blocks {
          style
        }
      }
    }
  }
}

Most of the fields under "blocks" are null. The only way I've been able to get the content I need out of this particular example is by using _rawModules at the root level. This isn't ideal since I'm already querying for each type of module using inline fragments and including the raw data is just doubling up on that and adding extra data I don't want.

The official GraphQL API seems to allow outputting raw json at a nested level, I've confirmed this via the playground with the following query:

query {
  allPages {
    modules {
    	... on RichText {
        blocksRaw
      }
    }
  }
}

Is it possible to implement this same behaviour in the Gatsby plugin?

Documents with _type that matches Sanity’s predefined object types break builds

We had an instance where there was a document like this in the dataset:

{
      "_createdAt": "<redacted>",
      "_id": "<redacted>",
      "_rev": "<redacted>",
      "_type": "slug",
      "_updatedAt": "<redacted>",
      "current": "test"
    }

Likely coming from adding an entry of the default objects that appear in the studio if no schema config is given. This confuses the source plugin, which then returns:

warning Type `SanitySlug` declared in `createTypes` looks like a node, but doesn't implement a `Node` interface. It's likely that you should add the `Node` interface to your type def:

`type SanitySlug implements Node { ... }`

If you know that you don't want it to be a node (which would mean no root queries to retrieve it), you can explicitly disable inference for it:

`type SanitySlug @dontInfer { ... }`
error Building schema failed

The best solution is probably to not show default object types in the studio in the first place, since you rarely want document representations of these. But we should consider if the source plugin should be able to anticipate that this can occur and at least give some helpful feedback to deal with it?

getFluidGatsbyImage return srcset with images smaller than the width of original image

I have an image asset uploaded which is 1440px x 640px. When I call getFluidGatsbyImagewith maxWidth set to 1440px, the function returns srcset with images of 360w and 720w and 1440w is missing, which result in low resolution imgae in my gatsby site.

I looked into the source code and I believe it is this line that filters out the width of original image. May I know if it is intended or not?

Add support for tracedSVG

Is there any specific reason it's not supported right now?
According to the gatsby-image docs, only these options are supported:

gatsby-source-sanity

  • GatsbySanityImageFixed
  • GatsbySanityImageFixed_noBase64
  • GatsbySanityImageFluid
  • GatsbySanityImageFluid_noBase64

Unable to add custom fields

Using onCreateNode in gatsby-node, I’m trying to use a transformer to compile and denormalize some data and then add this new value to the node with createNodeField. The process work fine but the fields object is not appended on my graphql schema.

@rexxars told me (on the Slack channel) that this was intentional, but I really need the ability to transform data at compile time.

How does the root field get set?

Given a queries array…

queries: [
  {
    name: 'movies',
    groq: `
      *[_type == 'movie']{
        _id,
        title
      }
    `
  },
]

…what would the root field get set as?

A query…

<StaticQuery
  query={graphql`
    query {
      SanityMovies {
        …
      }
    }
  `}
  …

…just returns GraphQL Error Unknown field 'SanityMovies' on type 'Query'

Kinda missing an example in docs, as it's not really that intuitive when you first get into it.

Unions from reference field with multiple types doesn't show in the Gatsby GraphQL API

If you have a reference field from Sanity that supports multiple types, e.g.

{
  name: 'aReference',
  type: 'reference',
  of: [{type: 'aType'},{type: 'anotherType'}]
}

This will work fine in Sanity’s GrahpQL layer: aReference (union aTypeorAnotherType)

In Gatsby’s internal API it will resolve to aReference (SanityAnotherType), i.e. just one of the types. It doesn't matter if there's data for both or not.

Watch mode stops working after a while

Is there a timeout for watch-mode? I'm using it without using overlayDrafts and when I first boot Gatsby it seems like everything works fine, but after a while (hours, perhaps?) the live updating will stop working. Refreshing the page won't result in new information being pulled after this, either—I have to reboot Gatsby in order to get new information from Sanity.

Add <link preconnect> for Sanity image API

I was doing some profiling for the new themejam site and noticed that loading the first image from Sanity's image API takes some time due to needing to connect to a new domain.

It'd speed things up a lot if sites using gatsby-source-sanity add <link href="https://cdn.sanity.io/" rel="preconnect" crossorigin>. It then occurred to me that this plugin could just do that for each site in gatsby-ssr.js :-)

Throttle watchMode

Is there some way to not have the watchMode trigger on every keyChange, but maybe on every page reload? As it is now, it triggers a huge amount of api-calls to sanity, which is not always a good thing.

fluid field missing when using using resolveReferences

Describe the bug

The fluid field is not returned when using resolveReferences. I have have a block in my page and I can see most other fields(ex. metadata, extension, etc) on the sanityImageAsset but I can’t get to the fluid .

To Reproduce

Example query:

{
  sanityPage(id: {eq: "c3cd53ba-ad81-53d2-8c73-5b218c1bc59f"}) {
    title
    _rawBody(resolveReferences: {maxDepth: 20})
  }
}

Expected behavior

Return a fluid field to be used with gatsby-image

Screenshots

image

Which versions of Sanity are you using?

@sanity/cli 1.149.4 (up to date)
@sanity/base 1.149.3 (latest: 1.149.5)
@sanity/cli 1.149.2 (latest: 1.149.4)
@sanity/components 1.149.3 (latest: 1.149.5)
@sanity/core 1.149.2 (latest: 1.149.4)
@sanity/dashboard 1.149.3 (latest: 1.149.5)
@sanity/default-layout 1.149.3 (latest: 1.149.5)
@sanity/default-login 1.148.1 (latest: 1.149.0)
@sanity/desk-tool 1.149.3 (latest: 1.149.5)

What operating system are you using?
MacOS 10.15.14

Which versions of Node.js / npm are you running?

6.14.1
v10.18.0

Additional context

https://sanity-io-land.slack.com/archives/C9Z7RC3V1/p1581994635422600

Root object schema does not implement the Gatsby Node interface

Hi.

I'm chasing down an error that's being thrown by Gatsby during the build process.
Apologies in advance in case some of my assumptions below are wrong, but here goes:

info [sanity] Fetching remote GraphQL schema
info [sanity] Transforming to Gatsby-compatible GraphQL SDL
info [sanity] Stitching GraphQL schemas from SDL
success onPreBootstrap — 0.236 s
info [sanity] Fetching export stream for dataset
info [sanity] Watch mode enabled, starting a listener
info [sanity] Done exporting!
success source and transform nodes — 0.664 s
warning Type `SanityArticle` declared in `createTypes` looks like a node, but doesn't implement a `Node` interface. It's likely that you should add the `Node` interface to your type def:

`type SanityArticle implements Node { ... }`

If you know that you don't want it to be a node (which would mean no root queries to retrieve it), you can explicitly disable inference for it:

`type SanityArticle @dontInfer { ... }`
error Building schema failed
error Command failed with exit code 1.

It seams like an error gets thrown because I have defined an Article model of type object (instead of document), but I have included this model as a "root schema" in the sanity schema configuration:

// schemas/schema.js
export default createSchema({
  name: "default",
  types: schemaTypes.concat([
    article: {
      type: "object",
      name: "article",
      title: "Article",
      fields: [
        {
          type: "string",
          name: "title",
          title: "Title"
        },
        {
          type: "string",
          name: "content",
          title: "Content"
        }
      ]
    },
    page: {
      type: "document",
      name: "page",
      title: "Page",
      fields: [
          {
          type: "string",
          name: "title",
          title: "Title"
        },
        {
          type: "article",
          name: "article",
          title: "Article"
        }
      ]
    }
  ])
})

While debugging, I'm seeing that the schema SDL that gets generated here becomes something something like this:

type SanityArticle {
  _key: String
  _type: String
  title: String
  content: String
}

type SanityPage implements SanityDocument & Node {
  _id: String
  _type: String
  _createdAt: Date
  _updatedAt: Date
  _rev: String
  _key: String
  title: String
  article: SanityArticle
}

"""
A Sanity document
"""
interface SanityDocument {
  _id: String
  _type: String
  _createdAt: Date
  _updatedAt: Date
  _rev: String
}

Which is why we see the error above.
From here, we can test the two different suggestions from the error message:

Implement the Node interface:

I attempted to remove this check, this resulted in a successful build/develop, and I could query the data like this:

query {
  allSanityArticle {
    ...
  }  
}

However, this naive approach is not a solution, since any object type would then be available in the generated SDL (the check is obviously there for a reason).

Disable inference with @dontInfer:

This also results in a successful develop/build, but I will not be able to execute a query for allSanityArticle.

What's the right solution to this problem?

What I would prefer is to extend the SanityArticle type with implements Node (and any other "root object types") so that I can query these in my Gatsby application (basically, treat "root object types" similar to "document types").

Note that, in this case, it is possible to remodel the application data (i.e. making the Article a "document", but that's still not a solution to this problem).

Help would be much appreciated!

required fields turn optional

When I add my sanity project to gatsby using this package, it turns all my required fields optional in the gatsby graphql server. Is this a known bug or is there any additional configuration that I need to add?

It's very unexpected, because the graphql server deployed by sanity does have fields properly marked as required in the schema.

Please feel free to try using the following config in gatsby-config.js

{
      resolve: 'gatsby-source-sanity',
      options: {
        projectId: '8kitcdai',
        dataset: 'development', 
      },
    }

How do I output block content

I see that there are two different references to my block content field, one is _rawProjectDesc and the other is just projectDesc The query I am playing with in graphiQL looks like this. Which am I supposed to use to get the block content, projectDesc.sanityChildren.text or the _rawProjectDesc only the raw is outputting data right now. And if someone could point me in the direction of once I get the whole block content how to use this https://www.npmjs.com/package/@sanity/block-content-to-react

Thanks ahead of time.

query MyQuery {
  allSanityBlogPost {
    edges {
      node {
        scopeMainTitle
        projectDesc {
          _key
          _type
          style
          list
          sanityChildren {
            _key
            _type
            text
          }
        }
        scopes {
          _key
          _type
          scopeValue
        }
        _rawProjectDesc(resolveReferences: {maxDepth: 10})
      }
    }
  }
}

Update:

I seem to have gotten something working with the serializer, is this the recommended way to do things, grab the raw field?

<BlockContent blocks={post._rawProjectDesc} serializers={serializers} />

Gatsby doesn't auto build and reload on data change

I don't see any changes with my gatsby when I edit my datasource. I tried with both 2.3.10 version and the latest. But i can see the content update when I close and rebuild it.

I initially thought it was a problem with using typescript. But i tried it with the gatsby starter and yet its the same behavior. Anything I'm missing here? My code looks like this -

gatsby-config.js

   {
      resolve: "gatsby-source-sanity",
      options: {
        projectId: "hqo6asqu",
        dataset: "production",
      },
    },

page/index.js

const IndexPage = ({
  data: {
    allSanityCourse: { nodes: courses },
  },
}) => (
  <Layout darkMode={true}>
    <SEO title="Home" keywords={[`gatsby`, `application`, `react`]} />

    {courses.map((course, index) => (
      <h1 key={index}>{course.title}</h1>
    ))}
    <Link to="/page-2/">Go to page 2</Link>
  </Layout>
);

export default IndexPage;

export const query = graphql`
  query {
    allSanityCourse {
      nodes {
        title
      }
    }
  }
`;

Also worth mentioning that I get this console warning but i read in one of the issues that it can be ignored. Anything to do with this? -

react-hot-loader.development.js:2433 React-Hot-Loader: react-🔥-dom patch is not detected. React 16.6+ features may not work.

Resolving references

So I have a reference in Gatsby from one type to another. Is there currently a way to model this in GraphQL using two node types?

I have a

     type: 'array',
      of: [
        // Which this would allow inline-adding of items
        {type: 'reference', to: {type: 'callToAction'}},
      ],

By default, I only get the fields _key, _ref_, _type. I know I can change the GROQ query to pull in the relationship fields directly, but I'd like it point to the sanityCallToAction node instead.

Ability to Incorporate Images In Build's Static Assets

Instead of having image assets being served from cdn.sanity.io, is there an approach for the used image assets to be downloaded ad added to a production build? We would prefer to use our own CDN for caching assets.

resolveReferences for _raw fields has no impact

Not sure if duplicate of/related to:
#37

Seems like the _rawContent(resolveReferences: { maxDepth: 10 }) has no impact on exposing the specific refs.

Query on createPages (_rawContent) in gatsby
image

Logging raw query
image

Result of log in frontend
image

GraphQL and Sanity blocks nightmare

When you are using blocks to provide rich content to your Sanity editing experience, it produces a large amount of raw nested data. When with GROQ, it's easy to retrieve, GraphQL is another story.

If the GROQ query look like :

groq: `
*[_type == 'article']{
  _id,
  title,
  article_body
}
`

Your Gatsby GraphQL query will look like :

export const query = graphql`
  query articleQuery($slug: String!) {
    article(slug: { current: { eq: $slug } }) {
      id
      title
      article_body {
        _key
        _type
        style
        markDefs {
          _key
          _type
          href
        }
        children {
          _key
          _type
          text
          marks
        }
      }
    }
  }
`;

The structured sub-fields are not constant and depend on the content. For example, markDefs or even marks are not always here for very simple typed content. So we cannot predict the exact schema of this query...

I use @sanity/block-content-to-react to render the block field, but it needs every sub-fields nested below.

@hcavalieri Have you already encountered this case and/or have you some kind of solution ?

Copy Images in Gatsby build

Is it possibile to copy images in gatsby build instead of sourcing them from sanity dataset endpoint?
I can't find any options, maybe some workaround?

Images quality degraded when

Hello,

When using getFluidGatsbyImage from gatsby-source-sanity, the images returned are degraded.

Using const fluidProps = getFluidGatsbyImage(node.asset._ref, {maxWidth: 3000}, clientConfig.sanity) returns images with a lowered quality. The smaller the image, the worst the compression.

Screen Shot 2020-01-19 at 11 47 58

Expected behavior

When resizing the same image with css instead, the image renders with a good quality (screenshot of the rendered image resized with css): Screen Shot 2020-01-19 at 11 48 11

Question
Is there any way to enhance the quality of the images?
What else can I do to remedy to this?

Sanity version
@sanity/cli 0.147.3 (up to date)

Deleted document keep showing up in gql

Hello,

i have a weird pblm, i deleted some sample documents, then re started gatsby, and those deleted documents keep showing up > Zombie docs.
Is there a way to filter them? ex: status: "published"?
They don't show up in sanity studio though.

Typescript types not found using default module export

I'm surprised I haven't seen this mentioned anywhere, so maybe I'm missing something, but the TypeScript compiler is unable to find this module's type defs when importing as usual, e.g.:

import {getFluidGatsbyImage} from 'gatsby-source-sanity'

Adding a types property to package.json should solve the problem:

{
  ...
  "types": "lib-es5/index.d.ts"
}

I've been able to import gatsby-source-sanity/lib in my project which also solves the issue, but that doesn't seem like a great solution.

Gatsby unable to recognize gatsby-source-sanity plugin

Hey there! 👋

I recently created a Sanity project with some basic document types. All document types also have at least placeholder values included (i.e. nothing is "empty" in the Sanity project).

After setting up the Sanity project, I then began a new Gatsby site by running gatsby new. Once everything was installed and set up, I immediately ran yarn add gatsby-source-sanity and started setting up the gatsby-config.js file.

Here's what my gatsby-config.js looks like at this point:

require('dotenv').config()

module.exports = {
  siteMetadata: {
    title: `Gatsby Default Starter`,
    description: `Kick off your next, great Gatsby project with this default starter. This barebones starter ships with the main Gatsby configuration files you might need.`,
    author: `@gatsbyjs`,
  },
  plugins: [
    {
      resolve: 'gatsby-source-sanity',
      options: {
        projectId: '7gnb8e5o',
        dataset: 'production',
        token: process.env.SANITY_TOKEN,
        watchMode: true,
        overlayDrafts: true
      }
    },
    `gatsby-plugin-react-helmet`,
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `images`,
        path: `${__dirname}/src/images`,
      },
    },
    `gatsby-transformer-sharp`,
    `gatsby-plugin-sharp`,
    {
      resolve: `gatsby-plugin-manifest`,
      options: {
        name: `gatsby-starter-default`,
        short_name: `starter`,
        start_url: `/`,
        background_color: `#663399`,
        theme_color: `#663399`,
        display: `minimal-ui`,
        icon: `src/images/gatsby-icon.png`,
      },
    }
  ],
}

After that, I ran yarn develop to begin the Gatsby development server. Everything builds properly and the site loads, except that it does not allow me to query anything Sanity-related in the the GraphiQL explorer, nor can it query anything Sanity-related in the codebase itself.

Versions:

"gatsby": "^2.3.5",
"gatsby-image": "^2.0.37",
"gatsby-plugin-manifest": "^2.0.26",
"gatsby-plugin-offline": "^2.0.25",
"gatsby-plugin-react-helmet": "^3.0.11",
"gatsby-plugin-sharp": "^2.0.32",
"gatsby-source-filesystem": "^2.0.28",
"gatsby-source-sanity": "^2.0.3",
"gatsby-transformer-sharp": "^2.1.17",
"prop-types": "^15.7.2",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-helmet": "^5.2.0"

In summary:

  1. Set up a basic Sanity project (with sanity init)
  2. Set up basic Gatsby project (with gatsby new)
  3. Added gatsby-source-sanity
  4. Set up gatsby-config.js with the new resolver (see above)
  5. Ran yarn develop
  6. No luck being able to create Sanity-related queries.

getGatsbyImageProps, runtime error because of small bug

Getting a runtime error. It occurs when an undefined id is sent in. The error:

TypeError: Cannot read property 'split' of undefined
getBasicImageProps
http://localhost:8000/commons.js:27678:15

  27675 |   return false;
  27676 | }
  27677 | 
> 27678 | var _a = id.split('-'),
        |             ^  27679 |     assetId = _a[1],
  27680 |     dimensions = _a[2],
  27681 |     extension = _a[3];

This is because this guard is not correct:

  const hasId = !id || idPattern.test(id)
  if (!hasId) {
    return false
  }

It only returns false when id is a truthy string, which does not seem to be the intention.

Suggested replacement:

  if (!id || !idPattern.test(id)) {
   return false;
  }

I would make a PR, but earlier this year I couldn't get npm link to work properly seemingly because of some deep deps in this package.

getFixedGatsbyImage base64 null

Hey!

Is getFixedGatsbyImage() method capable of returning base64 image previews? Currently I am using it to fetch fixed images to display them using gatsby-image, but base64 property is always null.

Do I have to enable previews somewhere?

Response preview:

{base64: null, aspectRatio: 1.7, width: 1200, height: 675, src: "https://cdn.sanity.io/images/oslxrhwr/production/4af65ae375e4d12b2f1914e9f006294144fc398f-2560x1440.jpg?w=1200&h=675&fit=crop", ... }

Thanks for the help!

Leon

Gatsby props not guarded against

Using children, parent, internal and such for field names can lead to issues in Gatbsy. We apparently do not have any guards against these (at least this is the case for internal).

Should probably warn + rename the field if encountering it.

Crash if naming a Sanity schema type "imageAsset"/"fileAsset"

If you make the following schema type:

{
  "name": "imageAsset",
  "type": "image",
  "fields": [{
    "name": "alt",
    "type": "string"
  }]
}

...it will be prefixed with Sanity when rewriting it to Gatsby schema, which collides with our default SanityImageAsset (sanity.imageAsset) type. I imagine the same goes for any other sanity-internal types.

Retain Image Name Rather Than Generated Image Filename

I'm optimizing images for SEO and can't seem to solve this issue:

I'd like to keep the image filename somewhere within the final images filenames I've found the option for 'storeOriginalFilename' however I'm having trouble passing it to the final filenames of the generated images.


Example of sanity auto-generated filenames being indexed with Google:
If you google 7b1b7cc7a4cf094b24cfd1ea6a6fa224865bc9e0 you'll get the incredible hulk due to the filename at: https://www.knutmelvaer.no/


Is there an example or documentation on how to accomplish this? Thanks in advance.

resolveReferences not working with internal link annotation

I have created an internalLink type following the sanity documentation and as per the gotcha note about using internalLinks with a graphql api, I have created it as a separate type as follows:

export default {
    name: 'internalLink',
    type: 'object',
    title: 'Internal link',
    fields: [
      {
        name: 'reference',
        type: 'reference',
        title: 'Reference',
        to: [
          { type: 'helpTopic' },
          // other types you may want to link to
        ]
      }
    ]
  }

I have added it schema.js as follows:

import internalLink from './internalLink'

export default createSchema({
  name: 'default',
  types: schemaTypes.concat([
    internalLink,
    helpTopic,
    blockContent,
    figure,
    slideshow,
  ])
})

and added it to annotations as follows:

annotations: [
          {
            type: 'internalLink'
          }
        ]

When I use graphiql in Gatsby, if I do not use resolveReferences, then I get the unresolved references properly:

"markDefs": [
                {
                  "_key": "00a07e239d3d",
                  "_type": "internalLink",
                  "reference": {
                    "_ref": "7c635eee-0d98-5335-a376-4101922ca4b7",
                    "_type": "reference"
                  }
                }
              ]

however, when I use _rawBody(resolveReferences:{maxDepth:1000}), the reference does not get resolved and returns as null:

"markDefs": [
                {
                  "_key": "00a07e239d3d",
                  "_type": "internalLink",
                  "reference": null
                }
              ]

Is this a bug or is there something wrong that I am doing. I have tried going through the docs but cannot figure this out and the example gatsby sanity combo project does not have an internalLinks example.

Thanks for the help in advance.

Add support for inferred width with getFixedGatsbyImage

Currently if you don't specify a width for getFixedGatsbyImage it falls back to the default value exports.DEFAULT_FIXED_WIDTH. It would be great if you could omit this when specifying a height in the same way that you can when using graphql. For example the following query only specifies a height and the width is then inferred from the image dimensions.

file(relativePath: { eq: "images/logo.png" }) {
  childImageSharp {
    fixed(height: 24) {
      ...GatsbyImageSharpFixed
    }
  }
}

All of a sudden stuck on source and transform nodes

Hey all, running into a very frustrating problem here. I've gone through a ton of threads out there (i.e. #17131, #6654, #6385, etc) but nothing seems to work. All of a sudden when running either gatsby build or gatsby develop the process hangs at source and transform nodes. It has always worked without a hitch and the only thing that has changed since it last worked is the node version I am using. After troubleshooting, I saw that this only happens when gatsby-source-sanity is enabled.

Usually it just hangs without any sort of error message, but one time it actually output the following:

$ gatsby develop
success open and validate gatsby-configs - 0.042s
success load plugins - 0.527s
success onPreInit - 0.010s
success initialize cache - 0.075s
success copy gatsby files - 0.074s
info [sanity] Fetching remote GraphQL schema
info [sanity] Transforming to Gatsby-compatible GraphQL SDL
warn [sanity] Type `ProductCategory` has field with name `parent`, which
warn [sanity] Type `SanityAssetSourceData` has field with name `id`, which
info [sanity] Stitching GraphQL schemas from SDL
success onPreBootstrap - 0.542s
success createSchemaCustomization - 0.004s
info [sanity] Fetching export stream for dataset
not finished source and transform ⠼ source and transform nodes
[Error: ENOENT: no such file or directory, utime '/Users/kmcaloon/.config/gatsby/sites/ab40b7b51d281cd4ed4cb72e9d5e2649/recipesgraphqlserver.json.lock'] {
  errno: -2,
  code: 'ECOMPROMISED',
  syscall: 'utime',
  path: '/Users/kmcaloon/.config/gatsby/sites/ab40b7b51d281cd4ed4cb72e9d5e2649/recipesgraphqlserver.json.lock'
}
error Command failed with exit code 7.

Environment

  System:
    OS: macOS Mojave 10.14.6
    CPU: (8) x64 Intel(R) Core(TM) i7-4770HQ CPU @ 2.20GHz
    Shell: 3.2.57 - /bin/bash
  Binaries:
    Node: 14.4.0 - ~/.nvm/versions/node/v14.4.0/bin/node
    Yarn: 1.17.3 - ~/.yarn/bin/yarn
    npm: 6.14.5 - ~/.nvm/versions/node/v14.4.0/bin/npm
  Languages:
    Python: 2.7.16 - /usr/bin/python
  Browsers:
    Chrome: 83.0.4103.97
    Firefox: 76.0.1
    Safari: 13.1.1
  npmPackages:
    gatsby: 2.21.22 => 2.21.22
    gatsby-plugin-antd: ^2.1.0 => 2.2.0
    gatsby-plugin-compression: ^0.0.1 => 0.0.1
    gatsby-plugin-env-variables: ^1.0.1 => 1.0.2
    gatsby-plugin-google-analytics: ^2.1.35 => 2.3.3
    gatsby-plugin-groq: ^1.0.0-alpha.7 => 1.0.0-alpha.10
    gatsby-plugin-hotjar-tracking: ^1.0.0 => 1.1.0
    gatsby-plugin-import: ^2.1.4 => 2.1.5
    gatsby-plugin-loadable-components-ssr: ^1.0.7 => 1.1.0
    gatsby-plugin-manifest: ^2.0.29 => 2.4.10
    gatsby-plugin-netlify-cache: ^1.2.0 => 1.2.0
    gatsby-plugin-no-javascript: ^2.0.5 => 2.0.5
    gatsby-plugin-olark: ^1.0.0 => 1.0.0
    gatsby-plugin-preact: ^3.1.25 => 3.3.2
    gatsby-plugin-purgecss: ^4.0.1 => 4.0.1
    gatsby-plugin-react-helmet: ^3.0.12 => 3.3.3
    gatsby-plugin-root-import: ^2.0.5 => 2.0.5
    gatsby-plugin-sass: ^2.0.11 => 2.3.3
    gatsby-plugin-typescript: ^2.1.26 => 2.4.4
    gatsby-plugin-web-font-loader: ^1.0.4 => 1.0.4
    gatsby-plugin-webpack-bundle-analyzer: ^1.0.5 => 1.0.5
    gatsby-plugin-zopfli: ^1.3.2 => 1.3.2
    gatsby-query-params: ^1.1.0 => 1.2.1
    gatsby-source-filesystem: ^2.1.5 => 2.3.10
    gatsby-source-sanity: ^5.0.5 => 5.0.6
  npmGlobalPackages:
    gatsby-cli: 2.12.44

Other local gatsby+sanity sites still work on my machine. I've tried disabling some of the plugins, cleaning cache, removing yarn.lock and modules and installing from scratch, upgrading gatsby-cli, resizing terminal window which for some reason actually works for a lot of people?????, etc. I'm at a loss here, but was hoping maybe someone could make sense out of the error message referencing recipegraphqlserver.json.lock or pretty much any of this.

I realize most likely I will need to provide a repo that reproduces this error but thought I would check first.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.