Skip to content

Commit

Permalink
Merge pull request #707 from WPMedia/themes-1905
Browse files Browse the repository at this point in the history
THEMES-1905: Update signing script to handle failing promised fetches
  • Loading branch information
nschubach authored May 15, 2024
2 parents ca8e924 + 72b76f9 commit b28a164
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 11 deletions.
24 changes: 15 additions & 9 deletions utils/resizer/src/sign-images-in-ans-object/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,6 @@ const signImagesInANSObject =
const replacements = new Set()

const stringData = JSON.stringify(data, (key, value) => {
if (value === null || typeof value === 'undefined') {
return value
}
const { _id, type, auth, url } = value
if (!auth?.[resizerAppVersion] && type === 'image') {
replacements.add(_id || url)
Expand All @@ -27,14 +24,23 @@ const signImagesInANSObject =
query: { id },
ttl: 31536000,
independent: true,
}).then((auth) => ({ id, auth })),
})
.then((auth) => ({ id, auth }))
.catch(() => ({})),
),
).then((authResults) => {
const replaced = authResults.reduce(
(accumulator, { id, auth }) =>
accumulator.replace(new RegExp(`__replaceMe${id}__`, 'g'), auth.hash),
stringData,
)
const replaced = authResults
.filter(({ id, auth }) => id && auth)
.reduce(
(accumulator, { id, auth }) =>
accumulator.replace(
new RegExp(`__replaceMe${id}__`, 'g'),
auth.hash,
),
stringData,
)
.replace(/,*\s*"\d+"\s*:\s*"__replaceMe[^_]+__"/g, '')
.replace(/,"auth"\s*:\s*{\s*}/g, '')
return {
data: JSON.parse(replaced),
...rest,
Expand Down
16 changes: 14 additions & 2 deletions utils/resizer/src/sign-images-in-ans-object/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import signImagesInANSObject from '.'
const data = {
_id: '43UU6MCQERAMRPTD23B3CEXE7E',
type: 'story',
undefinedValue: undefined,
content_elements: [
{
_id: 'LJJSIEXMZ5FTDBP7PFHXI5A4XY',
Expand Down Expand Up @@ -71,10 +70,13 @@ const idAuthMap = {
},
}

const fetcher = jest.fn((id) => idAuthMap[id])
const fetcher = jest.fn((id) => Promise.resolve(idAuthMap[id]))
const cachedCall = jest.fn((cacheId, fetchMethod, options) =>
Promise.resolve(fetchMethod(options.query.id)),
)
const failingCachedCall = jest.fn((cacheId, fetchMethod, options) =>
Promise.reject(fetchMethod(options.query.id)),
)

describe('Sign Images In ANS Object', () => {
beforeEach(() => {
Expand Down Expand Up @@ -159,4 +161,14 @@ describe('Sign Images In ANS Object', () => {
'545c018dbf2bbc8e4488c7546167e6afacc259cf4fe0b2f28c8043990f689e41',
)
})

it('returns unmodified data for a failing fetch service', async () => {
const signIt = signImagesInANSObject(failingCachedCall, fetcher, 2)

const { data: signedData } = await signIt({ data })

expect(failingCachedCall).toHaveBeenCalledTimes(3)

expect(signedData).toMatchObject(data)
})
})

0 comments on commit b28a164

Please sign in to comment.