diff --git a/src/lib/purge_cache.ts b/src/lib/purge_cache.ts index bb9067f5..af7b74aa 100644 --- a/src/lib/purge_cache.ts +++ b/src/lib/purge_cache.ts @@ -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( @@ -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) { diff --git a/test/unit/purge_cache.js b/test/unit/purge_cache.js index d3b97dfc..6fd0ef7f 100644 --- a/test/unit/purge_cache.js +++ b/test/unit/purge_cache.js @@ -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(() => { @@ -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) +})