Skip to content

Commit 1c99d34

Browse files
authored
fix(gatsby-plugin-sharp): use contentdigest for base64 cache (#24892)
* add test for base64 cache * use contentdigest
1 parent fe04c7f commit 1c99d34

File tree

2 files changed

+30
-4
lines changed

2 files changed

+30
-4
lines changed

packages/gatsby-plugin-sharp/src/__tests__/index.js

+28-3
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
const path = require(`path`)
2-
const sharp = require(`sharp`)
32
const fs = require(`fs-extra`)
43
jest.mock(`../scheduler`)
54

@@ -16,6 +15,7 @@ jest.mock(`gatsby/dist/redux/actions`, () => {
1615
}
1716
})
1817

18+
const sharp = require(`sharp`)
1919
const { scheduleJob } = require(`../scheduler`)
2020
scheduleJob.mockReturnValue(Promise.resolve())
2121
fs.ensureDirSync = jest.fn()
@@ -483,6 +483,31 @@ describe(`gatsby-plugin-sharp`, () => {
483483

484484
expect(result).toMatchSnapshot()
485485
})
486+
487+
it(`should cache same image`, async () => {
488+
const file1 = getFileObject(absolutePath)
489+
const file2 = getFileObject(absolutePath)
490+
const file3 = getFileObject(absolutePath, `test`, `new-image`)
491+
// change file of file3
492+
file3.base = path.join(__dirname, `images/144-density.png`)
493+
494+
const result = await base64({
495+
file: file1,
496+
args,
497+
})
498+
const result2 = await base64({
499+
file: file2,
500+
args,
501+
})
502+
const result3 = await base64({
503+
file: file3,
504+
args,
505+
})
506+
507+
// I would like to test sharp being executed but I don't really know how to mock that beast :p
508+
expect(result).toEqual(result2)
509+
expect(result).not.toEqual(result3)
510+
})
486511
})
487512

488513
describe(`image quirks`, () => {
@@ -578,7 +603,7 @@ describe(`gatsby-plugin-sharp`, () => {
578603
})
579604
})
580605

581-
function getFileObject(absolutePath, name = `test`) {
606+
function getFileObject(absolutePath, name = `test`, contentDigest = `1234`) {
582607
const parsedPath = path.parse(absolutePath)
583608
return {
584609
id: `${absolutePath} absPath of file`,
@@ -587,7 +612,7 @@ function getFileObject(absolutePath, name = `test`) {
587612
absolutePath,
588613
extension: `png`,
589614
internal: {
590-
contentDigest: `1234`,
615+
contentDigest,
591616
},
592617
}
593618
}

packages/gatsby-plugin-sharp/src/index.js

+2-1
Original file line numberDiff line numberDiff line change
@@ -362,7 +362,8 @@ async function generateBase64({ file, args = {}, reporter }) {
362362
return base64output
363363
}
364364

365-
const generateCacheKey = ({ file, args }) => `${file.id}${JSON.stringify(args)}`
365+
const generateCacheKey = ({ file, args }) =>
366+
`${file.internal.contentDigest}${JSON.stringify(args)}`
366367

367368
const memoizedBase64 = _.memoize(generateBase64, generateCacheKey)
368369

0 commit comments

Comments
 (0)