Skip to content

Commit 57258ef

Browse files
feat: accept userAgent property in purgeCache method (#553)
1 parent 5117d38 commit 57258ef

File tree

2 files changed

+49
-4
lines changed

2 files changed

+49
-4
lines changed

src/lib/purge_cache.test.ts

+38
Original file line numberDiff line numberDiff line change
@@ -123,3 +123,41 @@ test('Ignores purgeCache if in local dev with no token or site', async () => {
123123

124124
expect(response).toBeUndefined()
125125
})
126+
127+
test('Accepts a custom user-agent', async () => {
128+
if (!hasFetchAPI) {
129+
console.warn('Skipping test requires the fetch API')
130+
131+
return
132+
}
133+
134+
const userAgent = 'Netlify'
135+
const mockSiteID = '123456789'
136+
const mockToken = '1q2w3e4r5t6y7u8i9o0p'
137+
138+
process.env.NETLIFY_PURGE_API_TOKEN = mockToken
139+
process.env.SITE_ID = mockSiteID
140+
141+
const mockAPI = new MockFetch().post({
142+
body: (payload: string) => {
143+
const data = JSON.parse(payload)
144+
145+
expect(data.site_id).toBe(mockSiteID)
146+
},
147+
headers: { Authorization: `Bearer ${mockToken}`, 'user-agent': userAgent },
148+
method: 'post',
149+
response: new Response(null, { status: 202 }),
150+
url: `https://api.netlify.com/api/v1/purge`,
151+
})
152+
153+
const myFunction = async () => {
154+
await purgeCache({ userAgent })
155+
}
156+
157+
globalThis.fetch = mockAPI.fetcher
158+
159+
const response = await invokeLambda(myFunction)
160+
161+
expect(response).toBeUndefined()
162+
expect(mockAPI.fulfilled).toBeTruthy()
163+
})

src/lib/purge_cache.ts

+11-4
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ interface BasePurgeCacheOptions {
55
deployAlias?: string
66
tags?: string[]
77
token?: string
8+
userAgent?: string
89
}
910

1011
interface PurgeCacheOptionsWithSiteID extends BasePurgeCacheOptions {
@@ -73,13 +74,19 @@ export const purgeCache = async (options: PurgeCacheOptions = {}) => {
7374
)
7475
}
7576

77+
const headers: Record<string, string> = {
78+
'Content-Type': 'application/json; charset=utf8',
79+
Authorization: `Bearer ${token}`,
80+
}
81+
82+
if (options.userAgent) {
83+
headers['user-agent'] = options.userAgent
84+
}
85+
7686
const apiURL = options.apiURL || 'https://api.netlify.com'
7787
const response = await fetch(`${apiURL}/api/v1/purge`, {
7888
method: 'POST',
79-
headers: {
80-
'Content-Type': 'application/json; charset=utf8',
81-
Authorization: `Bearer ${token}`,
82-
},
89+
headers,
8390
body: JSON.stringify(payload),
8491
})
8592

0 commit comments

Comments
 (0)