Skip to content

Instantly share code, notes, and snippets.

@nwoow
Created March 30, 2020 15:48
Show Gist options
  • Select an option

  • Save nwoow/2c96e007d6d2f037afebb568eb9050cb to your computer and use it in GitHub Desktop.

Select an option

Save nwoow/2c96e007d6d2f037afebb568eb9050cb to your computer and use it in GitHub Desktop.
addEventListener('fetch', event => {
event.respondWith(handleRequest(event))
})
const BUCKET_NAME = 'modistabox-cdn'
const BUCKET_URL = `http://storage.googleapis.com/${BUCKET_NAME}`
async function serveAsset(event) {
const url = new URL(event.request.url)
const cache = caches.default
let response = await cache.match(event.request)
let device = event.request.headers.get('User-Agent')
console.log(`${BUCKET_URL}${url.pathname}`);
if (!response) {
response = await fetch(`${BUCKET_URL}${url.pathname}`, {
cf: {
image: {
fit: "scale-down",
width: 800,
height: 600,
}
}
})
const headers = { 'cache-control': 'public, max-age=14400' }
response = new Response(response.body, { ...response, headers })
event.waitUntil(cache.put(event.request, response.clone()))
}
return response
}
async function handleRequest(event) {
if (event.request.method === 'GET') {
let response = await serveAsset(event)
if (response.status > 399) {
response = new Response(response.statusText, { status: response.status })
}
return response
} else {
return new Response('Method not allowed', { status: 405 })
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment