This repository has been archived by the owner on Aug 3, 2023. It is now read-only.
/
fetch-dedupe.js
93 lines (80 loc) · 2.2 KB
/
fetch-dedupe.js
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
// This is a cache of in-flight requests. Each request key maps to an
// array of Promises. When the request resolves, each promise in the
// array is pushed to.
let requests = {};
export function getRequestKey({ url, method, responseType, body }) {
return [url, method, responseType, body].join('||');
}
// Returns `true` if a request with `requestKey` is in flight,
// and `false` otherwise.
export function isRequestInFlight(requestKey) {
return Boolean(requests[requestKey]);
}
export function clearRequestCache() {
requests = {};
}
// This loops through all of the handlers for the request and either
// resolves or rejects them.
function resolveRequest({ requestKey, res, err }) {
const handlers = requests[requestKey];
handlers.forEach(handler => {
if (res) {
handler.resolve(res);
} else {
handler.reject(err);
}
});
// This list of handlers has been, well, handled. So we
// clear the handlers for the next request.
requests[requestKey] = null;
}
export function fetchDedupe(
input,
init,
{ requestKey, responseType, dedupe = true }
) {
let proxyReq;
if (dedupe) {
if (!requests[requestKey]) {
requests[requestKey] = [];
}
const handlers = requests[requestKey];
const requestInFlight = Boolean(handlers.length);
const requestHandler = {};
proxyReq = new Promise((resolve, reject) => {
requestHandler.resolve = resolve;
requestHandler.reject = reject;
});
handlers.push(requestHandler);
if (requestInFlight) {
return proxyReq;
}
}
const request = fetch(input, init).then(
res => {
// The response body is a ReadableStream. ReadableStreams can only be read a single
// time, so we must handle that in a central location, here, before resolving
// the fetch.
return res[responseType]().then(data => {
res.data = data;
if (dedupe) {
resolveRequest({ requestKey, res });
} else {
return res;
}
});
},
err => {
if (dedupe) {
resolveRequest({ requestKey, err });
} else {
return Promise.reject(err);
}
}
);
if (dedupe) {
return proxyReq;
} else {
return request;
}
}