ConzorKingKong / cloud-storage

53 stars 13 forks source link

Example with caching #5

Closed tencnivel closed 4 years ago

tencnivel commented 4 years ago

Can you give an example that uses caching?

I tried to do it by mimicking what is done here

but i cannot get a cf-cache-status: HIT

Here is my failed attempt:

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event))
})

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 })
  }
}

async function serveAsset(event) {
  const url = new URL(event.request.url)

  const cache = caches.default
  let response = await cache.match(event.request)

  if (!response) {
    const { method, body } = event.request
    url.hostname = bucket + hostname
    response = await aws.fetch(url, { method, body })
    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
}
tencnivel commented 4 years ago

actually it does work, it's just that I was using curl -I to call the URL which is not allowed by the worker. One should use check the cf-cache-status response header in a browser instead