Created
January 30, 2020 22:30
-
-
Save ernestofreyreg/7d04dea27c558eec8876b32919a6ff41 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { getAssetFromKV, mapRequestToAsset } from '@cloudflare/kv-asset-handler' | |
const DEBUG = false | |
addEventListener('fetch', event => { | |
try { | |
event.respondWith(handleEvent(event)) | |
} catch (e) { | |
if (DEBUG) { | |
return event.respondWith( | |
new Response(e.message || e.toString(), { | |
status: 500, | |
}), | |
) | |
} | |
event.respondWith(new Response('Internal Error', { status: 500 })) | |
} | |
}) | |
async function handleEvent(event) { | |
let options = {} | |
try { | |
if (DEBUG) { | |
// customize caching | |
options.cacheControl = { | |
bypassCache: true, | |
} | |
} | |
const commitSha = await CONTROL.get('show_commit') | |
options.mapRequestToAsset = handleCommitSha(commitSha) | |
return await getAssetFromKV(event, options) | |
} catch (e) { | |
// if an error is thrown try to serve the asset at 404.html | |
if (!DEBUG) { | |
try { | |
let notFoundResponse = await getAssetFromKV(event, { | |
mapRequestToAsset: req => new Request(`${new URL(req.url).origin}/404.html`, req), | |
}) | |
return new Response(notFoundResponse.body, { ...notFoundResponse, status: 404 }) | |
} catch (e) {} | |
} | |
return new Response(e.message || e.toString(), { status: 500 }) | |
} | |
} | |
function handleCommitSha(commitSha) { | |
return request => { | |
let defaultAssetKey = mapRequestToAsset(request) | |
let url = new URL(defaultAssetKey.url) | |
url.pathname = `/${commitSha}${url.pathname}` | |
return new Request(url.toString(), defaultAssetKey) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment