Skip to content

Commit

Permalink
feat(gatsby-source-contentful): enable image-cdn (#34831)
Browse files Browse the repository at this point in the history
Co-authored-by: veryspry <ehlinger.matt@gmail.com>
Co-authored-by: Tyler Barnes <tylerdbarnes@gmail.com>
  • Loading branch information
3 people committed Mar 1, 2022
1 parent 29b236b commit 46fe418
Show file tree
Hide file tree
Showing 11 changed files with 174 additions and 37 deletions.
42 changes: 42 additions & 0 deletions e2e-tests/contentful/cypress/integration/gatsby-image-cdn.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { parseSrcset } from "srcset"

const testConfig = {
retries: {
runMode: 2,
openMode: 0,
},
}

describe(`gatsby-image-cdn urls`, () => {
beforeEach(() => {
cy.visit("/gatsby-image-cdn").waitForRouteChange()
})

it(`creates a proper gatsby image cdn url`, testConfig, () => {
const type = "gatsby-image-cdn"

cy.get(`[data-cy="${type}"]`)
.find(".gatsby-image-wrapper > picture > img")
.each(($el, i) => {
cy.wrap($el).should("be.visible")
cy.wrap($el)
.should("have.attr", "srcset")
.and(srcset => {
expect(srcset).to.match(/_gatsby\/image/)

parseSrcset(srcset).forEach(({ url }) => {
const [, , , sourceUrl64, _args64, filename] = url.split(`/`)
const sourceUrl = window.atob(sourceUrl64)
expect(sourceUrl).to.equal(
"https://images.ctfassets.net/k8iqpp6u0ior/3BSI9CgDdAn1JchXmY5IJi/f97a2185b3395591b98008647ad6fd3c/camylla-battani-AoqgGAqrLpU-unsplash.jpg"
)
expect(filename).to.equal(
"camylla-battani-AoqgGAqrLpU-unsplash.jpg"
)
})
})

cy.wrap($el).matchImageSnapshot(`${type}-${i}`)
})
})
})
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions e2e-tests/contentful/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
"gatsby-cypress": "^1.3.0",
"is-ci": "^3.0.0",
"prettier": "2.2.1",
"srcset": "^5.0.0",
"start-server-and-test": "^1.7.1"
},
"repository": {
Expand Down
37 changes: 37 additions & 0 deletions e2e-tests/contentful/src/pages/gatsby-image-cdn.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { graphql } from "gatsby"
import { GatsbyImage } from "gatsby-plugin-image"
import * as React from "react"

import Layout from "../components/layout"
import Grid from "../components/grid"

const GatsbyPluginImagePage = ({ data }) => {
return (
<Layout>
<h1>Test Gatsby Image CDN</h1>
<h2>Gatsby Image CDN:</h2>
<Grid data-cy="gatsby-image-cdn">
<GatsbyImage image={data.default.gatsbyImage} alt="" />
</Grid>
</Layout>
)
}

export default GatsbyPluginImagePage

export const pageQuery = graphql`
query GatsbyImageCDNQuery {
default: contentfulAsset(
contentful_id: { eq: "3BSI9CgDdAn1JchXmY5IJi" }
node_locale: { eq: "en-US" }
) {
title
description
file {
fileName
url
}
gatsbyImage(width: 420)
}
}
`
3 changes: 3 additions & 0 deletions e2e-tests/contentful/src/pages/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ const IndexPage = () => (
<li>
<Link to="/gatsby-plugin-image">/gatsby-plugin-image</Link>
</li>
<li>
<Link to="/gatsby-image-cdn">/gatsby-image-cdn</Link>
</li>
<li>
<Link to="/download-local">/download-local</Link>
</li>
Expand Down
2 changes: 1 addition & 1 deletion packages/gatsby-source-contentful/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@
"gatsby": "^4.0.0-next",
"gatsby-plugin-image": "^2.0.0-next",
"gatsby-plugin-sharp": "^4.0.0-next",
"sharp": "^0.29.3"
"sharp": "^0.30.1"
},
"repository": {
"type": "git",
Expand Down
11 changes: 10 additions & 1 deletion packages/gatsby-source-contentful/src/__tests__/gatsby-node.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,16 @@ describe(`gatsby-node`, () => {
}),
touchNode: jest.fn(),
}
const schema = { buildObjectType: jest.fn(), buildInterfaceType: jest.fn() }
const schema = {
buildObjectType: jest.fn(() => {
return {
config: {
interfaces: [],
},
}
}),
buildInterfaceType: jest.fn(),
}
const store = {
getState: jest.fn(() => {
return { program: { directory: process.cwd() }, status: {} }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@ import _ from "lodash"
import { fetchContentTypes } from "./fetch"
import { createPluginConfig } from "./plugin-options"
import { CODES } from "./report"
import { resolveGatsbyImageData } from "./gatsby-plugin-image"
import { ImageCropFocusType, ImageResizingBehavior } from "./schemes"
import { stripIndent } from "common-tags"
import { addRemoteFilePolyfillInterface } from "gatsby-plugin-utils/polyfill-remote-file"

async function getContentTypesFromContentful({
cache,
Expand Down Expand Up @@ -90,27 +94,66 @@ export async function createSchemaCustomization(
},
extensions: { infer: false },
}),
schema.buildObjectType({
name: `ContentfulAsset`,
fields: {
contentful_id: { type: `String!` },
id: { type: `ID!` },
...(pluginConfig.get(`downloadLocal`)
? {
localFile: {
type: `File`,
extensions: {
link: {
from: `fields.localFile`,
},
},
]

const { getGatsbyImageFieldConfig } = await import(
`gatsby-plugin-image/graphql-utils`
)

contentfulTypes.push(
addRemoteFilePolyfillInterface(
schema.buildObjectType({
name: `ContentfulAsset`,
fields: {
contentful_id: { type: `String!` },
id: { type: `ID!` },
gatsbyImageData: getGatsbyImageFieldConfig(
async (...args) => resolveGatsbyImageData(...args, { cache }),
{
jpegProgressive: {
type: `Boolean`,
defaultValue: true,
},
resizingBehavior: {
type: ImageResizingBehavior,
},
cropFocus: {
type: ImageCropFocusType,
},
cornerRadius: {
type: `Int`,
defaultValue: 0,
description: stripIndent`
Desired corner radius in pixels. Results in an image with rounded corners.
Pass \`-1\` for a full circle/ellipse.`,
},
quality: {
type: `Int`,
defaultValue: 50,
},
}
: {}),
},
interfaces: [`ContentfulReference`, `Node`],
}),
]
),
...(pluginConfig.get(`downloadLocal`)
? {
localFile: {
type: `File`,
extensions: {
link: {
from: `fields.localFile`,
},
},
},
}
: {}),
},
interfaces: [`ContentfulReference`, `Node`],
}),
{
schema,
actions,
}
)
)

// Create types for each content type
contentTypeItems.forEach(contentTypeItem =>
Expand Down Expand Up @@ -145,7 +188,7 @@ export async function createSchemaCustomization(
id: { type: `ID!` },
},
interfaces: [`Node`],
extensions: { dontInfer: {} },
extensions: { infer: false },
})
)
}
Expand Down
15 changes: 2 additions & 13 deletions packages/gatsby-source-contentful/src/extend-node-type.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,9 @@
// @ts-check
import { stripIndent } from "common-tags"
import {
GraphQLBoolean,
GraphQLInt,
GraphQLJSON,
GraphQLList,
} from "gatsby/graphql"
import { GraphQLBoolean, GraphQLInt, GraphQLJSON } from "gatsby/graphql"

import { resolveGatsbyImageData } from "./gatsby-plugin-image"
import {
ImageCropFocusType,
ImageFormatType,
ImageLayoutType,
ImagePlaceholderType,
ImageResizingBehavior,
} from "./schemes"
import { ImageCropFocusType, ImageResizingBehavior } from "./schemes"

export async function setFieldsOnGraphQLNodeType({ type, cache }) {
if (type.name !== `ContentfulAsset`) {
Expand Down
8 changes: 7 additions & 1 deletion packages/gatsby-source-contentful/src/gatsby-node.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@
import _ from "lodash"
import origFetch from "node-fetch"
import fetchRetry from "@vercel/fetch-retry"
import { polyfillImageServiceDevRoutes } from "gatsby-plugin-utils/polyfill-remote-file"
export { setFieldsOnGraphQLNodeType } from "./extend-node-type"

import { maskText } from "./plugin-options"

export { createSchemaCustomization } from "./create-schema-customization"
export { sourceNodes } from "./source-nodes"
export { setFieldsOnGraphQLNodeType } from "./extend-node-type"

const fetch = fetchRetry(origFetch)

Expand Down Expand Up @@ -131,3 +132,8 @@ List of locales and their codes can be found in Contentful app -> Settings -> Lo
plugins: Joi.array(),
})
.external(validateContentfulAccess)

/** @type {import('gatsby').GatsbyNode["onCreateDevServer"]} */
export const onCreateDevServer = ({ app }) => {
polyfillImageServiceDevRoutes(app)
}
9 changes: 8 additions & 1 deletion packages/gatsby-source-contentful/src/normalize.js
Original file line number Diff line number Diff line change
Expand Up @@ -717,6 +717,7 @@ export const createAssetNodes = ({
localesFallback,
})

const file = assetItem.fields.file ? getField(assetItem.fields.file) : {}
const assetNode = {
contentful_id: assetItem.sys.id,
spaceId: space.sys.id,
Expand All @@ -725,7 +726,7 @@ export const createAssetNodes = ({
updatedAt: assetItem.sys.updatedAt,
parent: null,
children: [],
file: assetItem.fields.file ? getField(assetItem.fields.file) : null,
file,
title: assetItem.fields.title ? getField(assetItem.fields.title) : ``,
description: assetItem.fields.description
? getField(assetItem.fields.description)
Expand All @@ -737,6 +738,12 @@ export const createAssetNodes = ({
sys: {
type: assetItem.sys.type,
},
url: `https:${file.url}`,
placeholderUrl: `https:${file.url}?w=%width%&h=%height%`,
mimeType: file.contentType,
filename: file.fileName,
width: file.details?.image?.width,
height: file.details?.image?.height,
}

// Link tags
Expand Down

0 comments on commit 46fe418

Please sign in to comment.