aboutsummaryrefslogtreecommitdiff
path: root/src/get-request-cache-key.js
blob: 9c98cb5ab6e8414513c78689b3d914ba05841ba6 (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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import { normalizeUrl } from './normalize-url'

export async function getRequestCacheKey(request) {
  try {
    // Respect "pragma: no-cache" header
    const pragma = request.headers.get('pragma')
    if (pragma === 'no-cache') {
      return null
    }

    // Only cache readonly requests
    if (request.method !== 'GET' && request.method !== 'HEAD') {
      return null
    }

    // Respect "cache-control" header directives
    const cacheControl = request.headers.get('cache-control')
    if (cacheControl) {
      const directives = new Set(cacheControl.split(',').map((s) => s.trim()))
      if (directives.has('no-store') || directives.has('no-cache')) {
        return null
      }
    }

    const url = request.url
    const normalizedUrl = normalizeUrl(url)

    if (url !== normalizedUrl) {
      return normalizeRequestHeaders(
        new Request(normalizedUrl, { method: request.method })
      )
    }

    return normalizeRequestHeaders(new Request(request))
  } catch (err) {
    console.error('error computing cache key', request.method, request.url, err)
    return null
  }
}

const requestHeaderWhitelist = new Set([
  'cache-control',
  'accept',
  'accept-encoding',
  'accept-language',
  'user-agent'
])

function normalizeRequestHeaders(request) {
  const headers = Object.fromEntries(request.headers.entries())
  const keys = Object.keys(headers)

  for (const key of keys) {
    if (!requestHeaderWhitelist.has(key)) {
      request.headers.delete(key)
    }
  }

  return request
}