Skip to content

Instantly share code, notes, and snippets.

@ajoy39
Created November 9, 2021 17:50
Show Gist options
  • Save ajoy39/afb01bb5f7f0c6088a6306b8223700bd to your computer and use it in GitHub Desktop.
Save ajoy39/afb01bb5f7f0c6088a6306b8223700bd to your computer and use it in GitHub Desktop.
async function handleRequest(request) {
let url = new URL(request.url)
// make sure you set B2_BUCKET_NAME as an environment variable
let filename = url.pathname.substring(url.pathname.lastIndexOf('/')+1);
let escaped_name = encodeURIComponent(filename)
let escaped_path = url.pathname.replace(filename, escaped_name)
url.pathname = `/file/${process.env.B2_BUCKET}${url.pathname}`
url.hostname = 'f001.backblazeb2.com'
let b2_path = url.toString().replace(filename, escaped_name)
let modified = new Request(b2_path, request)
let response = await fetch(modified, {
cf: {
cacheKey: request.url,
cacheEverything: true
}
})
return response
}
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment