Skip to content
This repository was archived by the owner on Jun 9, 2025. It is now read-only.

Commit b0152f1

Browse files
committed
feat: accept userAgent property in purgeCache method
1 parent 53b7bd0 commit b0152f1

File tree

2 files changed

+49
-5
lines changed

2 files changed

+49
-5
lines changed

src/lib/purge_cache.ts

Lines changed: 11 additions & 4 deletions
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

test/unit/purge_cache.js

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@ test.serial('Ignores purgeCache if in local dev with no token or site', async (t
104104
const mockAPI = new MockFetch().post({
105105
body: () => {
106106
t.fail()
107-
}
107+
},
108108
})
109109
const myFunction = async () => {
110110
await purgeCache()
@@ -116,3 +116,40 @@ test.serial('Ignores purgeCache if in local dev with no token or site', async (t
116116

117117
t.is(response, undefined)
118118
})
119+
120+
test.serial('Accepts a custom user agent', async (t) => {
121+
if (!hasFetchAPI) {
122+
console.warn('Skipping test requires the fetch API')
123+
124+
return t.pass()
125+
}
126+
127+
const userAgent = 'Netlify'
128+
const mockSiteID = '123456789'
129+
const mockToken = '1q2w3e4r5t6y7u8i9o0p'
130+
131+
process.env.NETLIFY_PURGE_API_TOKEN = mockToken
132+
process.env.SITE_ID = mockSiteID
133+
134+
const mockAPI = new MockFetch().post({
135+
body: (payload) => {
136+
const data = JSON.parse(payload)
137+
138+
t.is(data.site_id, mockSiteID)
139+
},
140+
headers: { Authorization: `Bearer ${mockToken}`, 'user-agent': userAgent },
141+
method: 'post',
142+
response: new Response(null, { status: 202 }),
143+
url: `https://api.netlify.com/api/v1/purge`,
144+
})
145+
const myFunction = async () => {
146+
await purgeCache({ userAgent })
147+
}
148+
149+
globalThis.fetch = mockAPI.fetcher
150+
151+
const response = await invokeLambda(myFunction)
152+
153+
t.is(response, undefined)
154+
t.true(mockAPI.fulfilled)
155+
})

0 commit comments

Comments
 (0)