-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
77 lines (68 loc) · 2.43 KB
/
app.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
addEventListener("fetch", (event) => {
event.respondWith(handleRequest(event.request));
});
const getBaseURL = (hostname, pathname, referer) => {
const isStaging = hostname === "stg-media.openbeta.io";
const isStatic = pathname.startsWith("/_next/static");
// handling static frontend content
if (isStatic) {
// we use the referer to keep vercel previews working
if (referer) {
return referer.replace(/\/$/, "");
}
// otherwise we route to the standard staging/prod base url
if (isStaging) {
return "https://stg.openbeta.io";
}
return "https://openbeta.io";
}
// handling other photos stored in google
if (isStaging) {
return "https://storage.googleapis.com/openbeta-staging";
}
return "https://storage.googleapis.com/openbeta-prod";
};
/**
* Fetch and log a request
* @param {Request} request
*/
async function handleRequest(request) {
// Parse request URL to get access to query string
const url = new URL(request.url);
if (url.pathname.length < 2)
return new Response("Missing image", { status: 400 });
if (!/\.(jpe?g|png|gif|webp)$/i.test(url.pathname)) {
return new Response("Disallowed file extension", { status: 400 });
}
// Cloudflare-specific options are in the cf object.
let options = { cf: { image: {} } };
// Copy parameters from query string to request options.
// You can implement various different parameters here.
if (url.searchParams.has("w"))
options.cf.image.width = url.searchParams.get("w");
if (url.searchParams.has("q"))
options.cf.image.quality = url.searchParams.get("q");
if (url.searchParams.has("h"))
options.cf.image.height = url.searchParams.get("h");
// Your Worker is responsible for automatic format negotiation. Check the Accept header.
const accept = request.headers.get("Accept");
if (/image\/avif/.test(accept)) {
options.cf.image.format = "avif";
} else if (/image\/webp/.test(accept)) {
options.cf.image.format = "webp";
}
const baseURL = getBaseURL(
url.hostname,
url.pathname,
request.headers.get("referer"),
);
const imageURL = `${baseURL}${url.pathname}`;
// Build a request that passes through request headers
const imageRequest = new Request(imageURL, {
headers: request.headers,
});
let response = await fetch(imageRequest, options);
response = new Response(response.body, response);
response.headers.set("Cache-Control", "public, max-age=15552000");
return response;
}