UNPKG

5.59 kBMarkdownView Raw
1# Can I cache this?
2
3`CachePolicy` tells when responses can be reused from a cache, taking into account [HTTP RFC 7234](http://httpwg.org/specs/rfc7234.html) rules for user agents and shared caches. It's aware of many tricky details such as the `Vary` header, proxy revalidation, and authenticated responses.
4
5## Usage
6
7Cacheability of an HTTP response depends on how it was requested, so both `request` and `response` are required to create the policy.
8
9```js
10const policy = new CachePolicy(request, response, options);
11
12if (!policy.storable()) {
13 // throw the response away, it's not usable at all
14 return;
15}
16
17// Cache the data AND the policy object in your cache
18// (this is pseudocode, roll your own cache (lru-cache package works))
19letsPretendThisIsSomeCache.set(request.url, {policy, response}, policy.timeToLive());
20```
21
22```js
23// And later, when you receive a new request:
24const {policy, response} = letsPretendThisIsSomeCache.get(newRequest.url);
25
26// It's not enough that it exists in the cache, it has to match the new request, too:
27if (policy && policy.satisfiesWithoutRevalidation(newRequest)) {
28 // OK, the previous response can be used to respond to the `newRequest`.
29 // Response headers have to be updated, e.g. to add Age and remove uncacheable headers.
30 response.headers = policy.responseHeaders();
31 return response;
32}
33```
34
35It may be surprising, but it's not enough for an HTTP response to be [fresh](#yo-fresh) to satisfy a request. It may need to match request headers specified in `Vary`. Even a matching fresh response may still not be usable if the new request restricted cacheability, etc.
36
37The key method is `satisfiesWithoutRevalidation(newRequest)`, which checks whether the `newRequest` is compatible with the original request and whether all caching conditions are met.
38
39### Constructor options
40
41Request and response must have a `headers` property with all header names in lower case. `url`, `status` and `method` are optional (defaults are any URL, status `200`, and `GET` method).
42
43```js
44const request = {
45 url: '/',
46 method: 'GET',
47 headers: {
48 accept: '*/*',
49 },
50};
51
52const response = {
53 status: 200,
54 headers: {
55 'cache-control': 'public, max-age=7234',
56 },
57};
58
59const options = {
60 shared: true,
61 cacheHeuristic: 0.1,
62 ignoreCargoCult: false,
63};
64```
65
66If `options.shared` is true (default), then response is evaluated from perspective of a shared cache (i.e. `private` is not cacheable and `s-maxage` is respected). If `options.shared` is false, then response is evaluated from perspective of a single-user cache (i.e. `private` is cacheable and `s-maxage` is ignored).
67
68`options.cacheHeuristic` is a fraction of response's age that is used as a fallback cache duration. The default is 0.1 (10%), e.g. if a file hasn't been modified for 100 days, it'll be cached for 100*0.1 = 10 days.
69
70If `options.ignoreCargoCult` is true, common anti-cache directives will be completely ignored if the non-standard `pre-check` and `post-check` directives are present. These two useless directives are most commonly found in bad StackOverflow answers and PHP's "session limiter" defaults.
71
72### `storable()`
73
74Returns `true` if the response can be stored in a cache. If it's `false` then you MUST NOT store either the request or the response.
75
76### `satisfiesWithoutRevalidation(new_request)`
77
78This is the most important method. Use this method to check whether the cached response is still fresh in the context of the new request.
79
80If it returns `true`, then the given `request` matches the original response this cache policy has been created with, and the response can be reused without contacting the server. Note that the old response can't be returned without being updated, see `responseHeaders()`.
81
82If it returns `false`, then the response may not be matching at all (e.g. it's for a different URL or method), or may require to be refreshed first.
83
84### `responseHeaders()`
85
86Returns updated, filtered set of response headers to return to clients receiving the cached response. This function is necessary, because proxies MUST always remove hop-by-hop headers (such as `TE` and `Connection`) and update response `Age` to avoid doubling cache time.
87
88### `revalidationHeaders()`
89
90Returns updated, filtered set of request headers to send to the origin server to check if the cached response can be reused. With this set of headers, the origin server may return status 304 indicating the response is still fresh.
91
92### `timeToLive()`
93
94Returns approximate time in *milliseconds* until the response becomes stale (i.e. not fresh).
95
96After that time (when `timeToLive() <= 0`) the response might not be usable without revalidation. However, there are exceptions, e.g. a client can explicitly allow stale responses, so always check with `satisfiesWithoutRevalidation()`.
97
98### `toObject()`/`fromObject(json)`
99
100Chances are you'll want to store the `CachePolicy` object along with the cached response. `obj = policy.toObject()` gives a plain JSON-serializable object. `policy = CachePolicy.fromObject(obj)` creates an instance from it.
101
102# Yo, FRESH
103
104![satisfiesWithoutRevalidation](fresh.jpg)
105
106## Implemented
107
108* `Cache-Control` response header with all the quirks.
109* `Expires` with check for bad clocks.
110* `Pragma` response header.
111* `Age` response header.
112* `Vary` response header.
113* Default cacheability of statuses and methods.
114* Requests for stale data.
115* Filtering of hop-by-hop headers.
116* Basic revalidation request
117
118## Unimplemented
119
120* Revalidation of multiple representations
121* Updating of response after revalidation