Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,10 @@ export const query = graphql`

**Note**: we currently [don't support the `format` option of `gatsbyImageData`](https://github.com/sanity-io/gatsby-source-sanity/issues/134#issuecomment-951876221). 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](https://gatsby.dev/img). 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`
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
"axios": "^0.24.0",
"debug": "^4.3.2",
"gatsby-core-utils": "^3.3.0",
"gatsby-plugin-utils": "^2.0.0",
"gatsby-plugin-utils": "^3.5.0-next.0",
"get-stream": "^6.0.1",
"lodash": "^4.17.21",
"oneline": "^1.0.3",
Expand Down
27 changes: 25 additions & 2 deletions src/gatsby-node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import {
SourceNodesArgs,
} from 'gatsby'
import {GraphQLFieldConfig} from 'gatsby/graphql'
import {polyfillImageServiceDevRoutes} from 'gatsby-plugin-utils/polyfill-remote-file'
import {addRemoteFilePolyfillInterface} from 'gatsby-plugin-utils/polyfill-remote-file'
import gatsbyPkg from 'gatsby/package.json'
import {uniq} from 'lodash'
import oneline from 'oneline'
Expand Down Expand Up @@ -162,14 +164,30 @@ export const createResolvers: GatsbyNode['createResolvers'] = (
}

export const createSchemaCustomization: GatsbyNode['createSchemaCustomization'] = (
{actions}: CreateSchemaCustomizationArgs,
{actions, schema}: CreateSchemaCustomizationArgs,
pluginConfig: PluginConfig,
): any => {
const {createTypes} = actions
const graphqlSdlKey = getCacheKey(pluginConfig, CACHE_KEYS.GRAPHQL_SDL)
const graphqlSdl = stateCache[graphqlSdlKey]

createTypes(graphqlSdl)
createTypes([
graphqlSdl,
/**
* The following type is for the Gatsby Image CDN resolver `gatsbyImage`. SanityImageAsset already exists in `graphqlSdl` above and then this type will be merged into it, extending it with image CDN support.
*/
addRemoteFilePolyfillInterface(
schema.buildObjectType({
name: `SanityImageAsset`,
fields: {},
interfaces: [`Node`, `RemoteFile`],
}),
{
schema,
actions,
},
),
])
}

export const sourceNodes: GatsbyNode['sourceNodes'] = async (
Expand All @@ -194,6 +212,7 @@ export const sourceNodes: GatsbyNode['sourceNodes'] = async (
createContentDigest,
createParentChildLink,
overlayDrafts,
client,
}

// PREVIEW UPDATES THROUGH WEBHOOKS
Expand Down Expand Up @@ -389,3 +408,7 @@ function getClient(config: PluginConfig) {
useCdn: false,
})
}

export const onCreateDevServer = async ({app}: {app: any}) => {
polyfillImageServiceDevRoutes(app)
}
32 changes: 31 additions & 1 deletion src/util/normalize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ import {safeId, unprefixId} from './documentIds'
import {TypeMap} from './remoteGraphQLSchema'
import {SanityInputNode} from '../types/gatsby'

import imageUrlBuilder from '@sanity/image-url'
import {SanityClient} from '@sanity/client'

const scalarTypeNames = specifiedScalarTypes.map((def) => def.name).concat(['JSON', 'Date'])

// Movie => SanityMovie
Expand All @@ -22,6 +25,7 @@ export interface ProcessingOptions {
createContentDigest: NodePluginArgs['createContentDigest']
createParentChildLink: Actions['createParentChildLink']
overlayDrafts: boolean
client: SanityClient
}

// Transform a Sanity document into a Gatsby node
Expand All @@ -31,13 +35,39 @@ export function toGatsbyNode(doc: SanityDocument, options: ProcessingOptions): S
const rawAliases = getRawAliases(doc, options)
const safe = prefixConflictingKeys(doc)
const withRefs = rewriteNodeReferences(safe, options)
const type = getTypeName(doc._type)
const urlBuilder = imageUrlBuilder(options.client)

const gatsbyImageCdnFields = [`SanityImageAsset`, `SanityFileAsset`].includes(type)
? {
filename: withRefs.originalFilename,
width: withRefs?.metadata?.dimensions?.width,
height: withRefs?.metadata?.dimensions?.height,
url: withRefs?.url,
placeholderUrl:
type === `SanityImageAsset`
? urlBuilder
.image(withRefs.url)
.width(20)
.height(30)
.quality(80)
.url()
// this makes placeholder urls dynamic in the gatsbyImage resolver
?.replace(`w=20`, `w=%width%`)
?.replace(`h=30`, `h=%height%`)
: null,
}
: {}

return {
...withRefs,
...rawAliases,
...gatsbyImageCdnFields,

id: safeId(overlayDrafts ? unprefixId(doc._id) : doc._id, createNodeId),
children: [],
internal: {
type: getTypeName(doc._type),
type,
contentDigest: createContentDigest(JSON.stringify(withRefs)),
},
}
Expand Down