diff --git a/src/lib/purge_cache.test.ts b/src/lib/purge_cache.test.ts index f8bb2266..04871c56 100644 --- a/src/lib/purge_cache.test.ts +++ b/src/lib/purge_cache.test.ts @@ -123,3 +123,41 @@ test('Ignores purgeCache if in local dev with no token or site', async () => { expect(response).toBeUndefined() }) + +test('Accepts a custom user-agent', async () => { + if (!hasFetchAPI) { + console.warn('Skipping test requires the fetch API') + + return + } + + const userAgent = 'Netlify' + const mockSiteID = '123456789' + const mockToken = '1q2w3e4r5t6y7u8i9o0p' + + process.env.NETLIFY_PURGE_API_TOKEN = mockToken + process.env.SITE_ID = mockSiteID + + const mockAPI = new MockFetch().post({ + body: (payload: string) => { + const data = JSON.parse(payload) + + expect(data.site_id).toBe(mockSiteID) + }, + headers: { Authorization: `Bearer ${mockToken}`, 'user-agent': userAgent }, + method: 'post', + response: new Response(null, { status: 202 }), + url: `https://api.netlify.com/api/v1/purge`, + }) + + const myFunction = async () => { + await purgeCache({ userAgent }) + } + + globalThis.fetch = mockAPI.fetcher + + const response = await invokeLambda(myFunction) + + expect(response).toBeUndefined() + expect(mockAPI.fulfilled).toBeTruthy() +}) diff --git a/src/lib/purge_cache.ts b/src/lib/purge_cache.ts index af7b74aa..f88c905a 100644 --- a/src/lib/purge_cache.ts +++ b/src/lib/purge_cache.ts @@ -5,6 +5,7 @@ interface BasePurgeCacheOptions { deployAlias?: string tags?: string[] token?: string + userAgent?: string } interface PurgeCacheOptionsWithSiteID extends BasePurgeCacheOptions { @@ -73,13 +74,19 @@ export const purgeCache = async (options: PurgeCacheOptions = {}) => { ) } + const headers: Record = { + 'Content-Type': 'application/json; charset=utf8', + Authorization: `Bearer ${token}`, + } + + if (options.userAgent) { + headers['user-agent'] = options.userAgent + } + const apiURL = options.apiURL || 'https://api.netlify.com' const response = await fetch(`${apiURL}/api/v1/purge`, { method: 'POST', - headers: { - 'Content-Type': 'application/json; charset=utf8', - Authorization: `Bearer ${token}`, - }, + headers, body: JSON.stringify(payload), })