-
Notifications
You must be signed in to change notification settings - Fork 28
/
index.js
37 lines (33 loc) · 1.25 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// Based on https://developers.cloudflare.com/workers/tutorials/configure-your-cdn
addEventListener("fetch", event => {
event.respondWith(handleRequest(event))
})
const CLOUD_URL = `https://res.cloudinary.com/${CLOUD_NAME}/image`;
async function serveAsset(event) {
const url = new URL(event.request.url)
const cache = caches.default
let response = await cache.match(event.request)
if (!response) {
const cloudinaryURL = `${CLOUD_URL}${url.pathname}`;
response = await fetch(cloudinaryURL, { headers: event.request.headers })
// Cache for however long, here is 4 hours.
const headers = new Headers(response.headers);
headers.set("cache-control", `public, max-age=14400`);
headers.set("vary", "Accept");
response = new Response(response.body, { ...response, headers })
event.waitUntil(cache.put(event.request, response.clone()))
}
return response
}
async function handleRequest(event) {
console.log('Requesting the image')
if (event.request.method === "GET") {
let response = await serveAsset(event)
if (response.status > 399) {
response = new Response(response.statusText, { status: response.status })
}
return response
} else {
return new Response("Method not allowed", { status: 405 })
}
}