Thanks to visit codestin.com
Credit goes to github.com

Skip to content
This repository was archived by the owner on Jun 9, 2025. It is now read-only.

fix: skip purgeCache in local dev #472

Merged
merged 2 commits into from
Feb 13, 2024
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
7 changes: 7 additions & 0 deletions src/lib/purge_cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ interface PurgeAPIPayload {
site_slug?: string
}

// eslint-disable-next-line complexity
export const purgeCache = async (options: PurgeCacheOptions = {}) => {
if (globalThis.fetch === undefined) {
throw new Error(
Expand All @@ -42,6 +43,12 @@ export const purgeCache = async (options: PurgeCacheOptions = {}) => {
}
const token = env.NETLIFY_PURGE_API_TOKEN || options.token

if (env.NETLIFY_LOCAL && !token) {
const scope = options.tags?.length ? ` for tags ${options.tags?.join(', ')}` : ''
console.log(`Skipping purgeCache${scope} in local development.`)
return
}

if ('siteSlug' in options) {
payload.site_slug = options.siteSlug
} else if ('domain' in options) {
Expand Down
26 changes: 26 additions & 0 deletions test/unit/purge_cache.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ const hasFetchAPI = semver.gte(process.version, '18.0.0')
test.beforeEach(() => {
delete process.env.NETLIFY_PURGE_API_TOKEN
delete process.env.SITE_ID
delete process.env.NETLIFY_LOCAL
})

test.afterEach(() => {
Expand Down Expand Up @@ -90,3 +91,28 @@ test.serial('Throws if the API response does not have a successful status code',
'Cache purge API call returned an unexpected status code: 500',
)
})

test.serial('Ignores purgeCache if in local dev with no token or site', async (t) => {
if (!hasFetchAPI) {
console.warn('Skipping test requires the fetch API')

return t.pass()
}

process.env.NETLIFY_LOCAL = '1'

const mockAPI = new MockFetch().post({
body: () => {
t.fail()
}
})
const myFunction = async () => {
await purgeCache()
}

globalThis.fetch = mockAPI.fetcher

const response = await invokeLambda(myFunction)

t.is(response, undefined)
})