-
Notifications
You must be signed in to change notification settings - Fork 2k
/
Copy pathHTTPCache.ts
167 lines (143 loc) · 4.9 KB
/
HTTPCache.ts
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
import { fetch, Request, Response, Headers } from 'apollo-server-env';
import CachePolicy = require('http-cache-semantics');
import { KeyValueCache, InMemoryLRUCache } from 'apollo-server-caching';
import { CacheOptions } from './RESTDataSource';
export class HTTPCache {
constructor(private keyValueCache: KeyValueCache = new InMemoryLRUCache()) {}
async fetch(
request: Request,
options: {
cacheKey?: string;
cacheOptions?:
| CacheOptions
| ((response: Response, request: Request) => CacheOptions | undefined);
} = {},
): Promise<Response> {
const cacheKey = options.cacheKey ? options.cacheKey : request.url;
const entry = await this.keyValueCache.get(`httpcache:${cacheKey}`);
if (!entry) {
const response = await fetch(request);
const policy = new CachePolicy(
policyRequestFrom(request),
policyResponseFrom(response),
);
return this.storeResponseAndReturnClone(
response,
request,
policy,
cacheKey,
options.cacheOptions,
);
}
const { policy: policyRaw, ttlOverride, body } = JSON.parse(entry);
const policy = CachePolicy.fromObject(policyRaw);
// Remove url from the policy, because otherwise it would never match a request with a custom cache key
policy._url = undefined;
if (
(ttlOverride && policy.age() < ttlOverride) ||
(!ttlOverride &&
policy.satisfiesWithoutRevalidation(policyRequestFrom(request)))
) {
const headers = policy.responseHeaders();
return new Response(body, {
url: policy._url,
status: policy._status,
headers,
});
} else {
const revalidationHeaders = policy.revalidationHeaders(
policyRequestFrom(request),
);
const revalidationRequest = new Request(request, {
headers: revalidationHeaders,
});
const revalidationResponse = await fetch(revalidationRequest);
const { policy: revalidatedPolicy, modified } = policy.revalidatedPolicy(
policyRequestFrom(revalidationRequest),
policyResponseFrom(revalidationResponse),
);
return this.storeResponseAndReturnClone(
new Response(modified ? await revalidationResponse.text() : body, {
url: revalidatedPolicy._url,
status: revalidatedPolicy._status,
headers: revalidatedPolicy.responseHeaders(),
}),
request,
revalidatedPolicy,
cacheKey,
options.cacheOptions,
);
}
}
private async storeResponseAndReturnClone(
response: Response,
request: Request,
policy: CachePolicy,
cacheKey: string,
cacheOptions?:
| CacheOptions
| ((response: Response, request: Request) => CacheOptions | undefined),
): Promise<Response> {
if (cacheOptions && typeof cacheOptions === 'function') {
cacheOptions = cacheOptions(response, request);
}
let ttlOverride = cacheOptions && cacheOptions.ttl;
if (
// With a TTL override, only cache succesful responses but otherwise ignore method and response headers
!(ttlOverride && (policy._status >= 200 && policy._status <= 299)) &&
// Without an override, we only cache GET requests and respect standard HTTP cache semantics
!(request.method === 'GET' && policy.storable())
) {
return response;
}
let ttl = ttlOverride || Math.round(policy.timeToLive() / 1000);
if (ttl <= 0) return response;
// If a response can be revalidated, we don't want to remove it from the cache right after it expires.
// We may be able to use better heuristics here, but for now we'll take the max-age times 2.
if (canBeRevalidated(response)) {
ttl *= 2;
}
const body = await response.text();
const entry = JSON.stringify({
policy: policy.toObject(),
ttlOverride,
body,
});
await this.keyValueCache.set(`httpcache:${cacheKey}`, entry, {
ttl,
});
// We have to clone the response before returning it because the
// body can only be used once.
// To avoid https://github.com/bitinn/node-fetch/issues/151, we don't use
// response.clone() but create a new response from the consumed body
return new Response(body, {
url: response.url,
status: response.status,
statusText: response.statusText,
headers: response.headers,
});
}
}
function canBeRevalidated(response: Response): boolean {
return response.headers.has('ETag');
}
function policyRequestFrom(request: Request) {
return {
url: request.url,
method: request.method,
headers: headersToObject(request.headers),
};
}
function policyResponseFrom(response: Response) {
return {
status: response.status,
headers: headersToObject(response.headers),
};
}
function headersToObject(headers: Headers) {
const object = Object.create(null);
for (const [name, value] of headers) {
object[name] = value;
}
return object;
}