|
| 1 | +function parseAcceptHeader(acceptHeader) { |
| 2 | + // generated by Google AI "parse accept header javascript" |
| 3 | + if (!acceptHeader) { |
| 4 | + return []; |
| 5 | + } |
| 6 | + |
| 7 | + return acceptHeader.split(',') |
| 8 | + .map(item => item.trim()) |
| 9 | + .map(item => { |
| 10 | + const parts = item.split(';'); |
| 11 | + const value = parts[0].trim(); |
| 12 | + let quality = 1; |
| 13 | + |
| 14 | + if (parts.length > 1) { |
| 15 | + const q = parts[1].trim(); |
| 16 | + if (q.startsWith('q=')) { |
| 17 | + quality = parseFloat(q.substring(2)); |
| 18 | + } |
| 19 | + } |
| 20 | + |
| 21 | + return { value, quality }; |
| 22 | + }) |
| 23 | + .sort((a, b) => b.quality - a.quality); |
| 24 | + // From: |
| 25 | + // text/html, application/xhtml+xml, application/xml;q=0.9, */*;q=0.8 |
| 26 | + // Expected output: |
| 27 | + // [ |
| 28 | + // { value: 'text/html', quality: 1 }, |
| 29 | + // { value: 'application/xhtml+xml', quality: 1 }, |
| 30 | + // { value: 'application/xml', quality: 0.9 }, |
| 31 | + // { value: '*/*', quality: 0.8 } |
| 32 | + // ] |
| 33 | +} |
| 34 | + |
1 | 35 | const typeToExt = {
|
2 | 36 | "text/turtle": "ttl",
|
3 | 37 | "application/ld+json": "jsonld"
|
4 | 38 | };
|
5 | 39 |
|
6 | 40 | export async function onRequest(context) {
|
7 | 41 | try {
|
8 |
| - const accept = context.request.headers.get('Accept'); |
| 42 | + const parsedAccept = parseAcceptHeader(context.request.headers.get('Accept')); |
| 43 | + const accept = parsedAccept[0].value; |
9 | 44 |
|
10 | 45 | // if we have a mapping for this extension, send it. Otherwise fall through.
|
11 | 46 | if(Object.keys(typeToExt).indexOf(accept) > -1) {
|
|
0 commit comments