-
Notifications
You must be signed in to change notification settings - Fork 155
/
Copy path_middleware.js
57 lines (51 loc) · 1.64 KB
/
_middleware.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
function parseAcceptHeader(acceptHeader) {
// generated by Google AI "parse accept header javascript"
if (!acceptHeader) {
return [];
}
return acceptHeader.split(',')
.map(item => item.trim())
.map(item => {
const parts = item.split(';');
const value = parts[0].trim();
let quality = 1;
if (parts.length > 1) {
const q = parts[1].trim();
if (q.startsWith('q=')) {
quality = parseFloat(q.substring(2));
}
}
return { value, quality };
})
.sort((a, b) => b.quality - a.quality);
// From:
// text/html, application/xhtml+xml, application/xml;q=0.9, */*;q=0.8
// Expected output:
// [
// { value: 'text/html', quality: 1 },
// { value: 'application/xhtml+xml', quality: 1 },
// { value: 'application/xml', quality: 0.9 },
// { value: '*/*', quality: 0.8 }
// ]
}
const typeToExt = {
"text/turtle": "ttl",
"application/ld+json": "jsonld"
};
export async function onRequest(context) {
try {
const parsedAccept = parseAcceptHeader(context.request.headers.get('Accept'));
const accept = parsedAccept[0].value;
// if we have a mapping for this extension, send it. Otherwise fall through.
if(Object.keys(typeToExt).indexOf(accept) > -1) {
const ext = typeToExt[accept] || `html`;
const rewrittenUrl = context.request.url + '.' + ext;
const asset = await context.env.ASSETS.fetch(rewrittenUrl);
const response = new Response(asset.body, asset);
return response;
}
return context.next();
} catch (err) {
return new Response(`${err.message}\n${err.stack}`, { status: 500 });
}
}