Skip to content

Instantly share code, notes, and snippets.

@mrmason
Created April 24, 2019 12:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrmason/eaf5495b70cbdaad329d297eb50d3977 to your computer and use it in GitHub Desktop.
Save mrmason/eaf5495b70cbdaad329d297eb50d3977 to your computer and use it in GitHub Desktop.
CF File Cache Worker
addEventListener('fetch', event => {
event.respondWith(handleRequest(event))
})
async function handleRequest(event) {
// try and find the file in cloudflare cache
let request = event.request
let cache = caches.default
let response = await cache.match(request)
if (!response) {
// File not found in Cache API so
// Set the response to be the file from B2
modRequest = new Request(request.url, {
method: request.method
})
response = await fetch(modRequest)
response = new Response(response.body, response)
// Remove/Rename the BZHeaders
try{
if(response.headers.get('x-bz-content-sha1') === 'none'){
response.headers.append('n-sha1', response.headers.get('x-bz-info-large_file_sha1'))
}else {
response.headers.append('n-sha1', response.headers.get('x-bz-content-sha1'))
}
response.headers.delete('x-bz-content-sha1')
response.headers.delete('x-bz-info-large_file_sha1')
response.headers.delete('x-bz-file-id')
response.headers.delete('x-bz-file-name')
response.headers.delete('x-bz-info-src_last_modified_millis')
response.headers.delete('x-bz-upload-timestamp')
}catch(ex){
response.headers.append('n-cache-err', ex.message)
}
// If this file is less than 490MB then add it to the cache
if (parseInt(response.headers.get('content-length')) < 513802240) {
// response.headers.append('Transfer-Encoding', 'chunked')
// response.headers.append('Cached-At', Date.now())
// Cache this file
event.waitUntil(cache.put(request, response.clone()))
}else{
response.headers.append('n-cache', 'file-over-500m')
}
// Set Cache Status
response.headers.append('n-cache', 'miss')
}else{
response.headers.append('n-cache', 'hit')
}
return response
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment