Skip to content

Commit

Permalink
feat: accept userAgent property in purgeCache method (#553)
Browse files Browse the repository at this point in the history
  • Loading branch information
eduardoboucas authored Dec 18, 2024
1 parent 5117d38 commit 57258ef
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 4 deletions.
38 changes: 38 additions & 0 deletions src/lib/purge_cache.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()
})
15 changes: 11 additions & 4 deletions src/lib/purge_cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ interface BasePurgeCacheOptions {
deployAlias?: string
tags?: string[]
token?: string
userAgent?: string
}

interface PurgeCacheOptionsWithSiteID extends BasePurgeCacheOptions {
Expand Down Expand Up @@ -73,13 +74,19 @@ export const purgeCache = async (options: PurgeCacheOptions = {}) => {
)
}

const headers: Record<string, string> = {
'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),
})

Expand Down

0 comments on commit 57258ef

Please sign in to comment.