aboutsummaryrefslogtreecommitdiff
path: root/src/fetch-cache.js
blob: 3fb68300acc2aac79ab3aafdecac6313aaabdda3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
const cache = caches.default

export async function fetchCache(opts) {
  const { event, cacheKey, fetch: fetchResponse } = opts

  let response

  if (cacheKey) {
    console.log('cacheKey', cacheKey.url)
    response = await cache.match(cacheKey)
  }

  if (!response) {
    response = await fetchResponse()
    response = new Response(response.body, response)

    if (cacheKey) {
      if (response.headers.has('Cache-Control')) {
        // cache will respect response headers
        event.waitUntil(
          cache.put(cacheKey, response.clone()).catch((err) => {
            console.warn('cache put error', cacheKey, err)
          })
        )
      }

      response.headers.set('cf-cache-status', 'MISS')
    } else {
      response.headers.set('cf-cache-status', 'BYPASS')
    }
  }

  return response
}