| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | const DELAY_BEFORE_FIRST_PURGE = 0 * 1000 |
| | const DELAY_BEFORE_SECOND_PURGE = 2 * 1000 |
| |
|
| | const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)) |
| |
|
| | async function purgeFastlyBySurrogateKey({ |
| | apiToken, |
| | serviceId, |
| | surrogateKey, |
| | }: { |
| | apiToken: string |
| | serviceId: string |
| | surrogateKey: string |
| | }) { |
| | const safeServiceId = encodeURIComponent(serviceId) |
| |
|
| | const headers = { |
| | 'fastly-key': apiToken, |
| | accept: 'application/json', |
| | 'fastly-soft-purge': '1', |
| | } |
| | const requestPath = `https://api.fastly.com/service/${safeServiceId}/purge/${surrogateKey}` |
| | const response = await fetch(requestPath, { |
| | method: 'POST', |
| | headers: { |
| | ...headers, |
| | 'Content-Type': 'application/json', |
| | }, |
| | }) |
| | if (!response.ok) { |
| | throw new Error(`HTTP ${response.status}: ${response.statusText}`) |
| | } |
| | return response |
| | } |
| |
|
| | export default async function purgeEdgeCache( |
| | surrogateKey: string, |
| | { |
| | purgeTwice = true, |
| | delayBeforeFirstPurge = DELAY_BEFORE_FIRST_PURGE, |
| | delayBeforeSecondPurge = DELAY_BEFORE_SECOND_PURGE, |
| | } = {}, |
| | ) { |
| | if (!surrogateKey) { |
| | throw new Error('No key set and/or no FASTLY_SURROGATE_KEY env var set') |
| | } |
| | console.log(`Fastly purgeEdgeCache initialized for: '${surrogateKey}'`) |
| |
|
| | const { FASTLY_TOKEN, FASTLY_SERVICE_ID } = process.env |
| | if (!FASTLY_TOKEN || !FASTLY_SERVICE_ID) { |
| | throw new Error('Fastly env vars not detected; skipping purgeEdgeCache step') |
| | } |
| |
|
| | const purgingParams = { |
| | apiToken: FASTLY_TOKEN, |
| | serviceId: FASTLY_SERVICE_ID, |
| | surrogateKey, |
| | } |
| |
|
| | |
| | |
| | if (delayBeforeFirstPurge) { |
| | console.log('Waiting extra time to prevent a Thundering Herd problem...') |
| | await sleep(delayBeforeFirstPurge) |
| | } |
| |
|
| | console.log('Attempting first Fastly purge...') |
| | const firstPurge = await purgeFastlyBySurrogateKey(purgingParams) |
| | console.log('First Fastly purge result:', firstPurge.body || firstPurge) |
| |
|
| | |
| | if (purgeTwice) { |
| | console.log('Waiting to purge a second time...') |
| | await sleep(delayBeforeSecondPurge) |
| |
|
| | console.log('Attempting second Fastly purge...') |
| | const secondPurge = await purgeFastlyBySurrogateKey(purgingParams) |
| | console.log('Second Fastly purge result:', secondPurge.body || secondPurge) |
| | } |
| | } |
| |
|