Skip to content

feat: accept userAgent property in purgeCache method #553

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Dec 18, 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
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
Loading