This repository has been archived by the owner on Jul 12, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 25
/
fetch-suspense.ts
219 lines (190 loc) · 5.42 KB
/
fetch-suspense.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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
import deepEqual = require('deep-equal');
type FetchFunction = typeof window.fetch;
type CreateUseFetch = (fetch?: FetchFunction) => UseFetch;
interface Export extends UseFetch {
createUseFetch: CreateUseFetch;
default: UseFetch;
}
interface FetchCache {
bodyUsed?: boolean;
contentType?: null | string;
fetch?: Promise<void>;
error?: any;
headers?: Headers;
init: RequestInit | undefined;
input: RequestInfo;
ok?: boolean;
redirected?: boolean;
response?: any;
status?: number;
statusText?: string;
url?: string;
}
type FetchResponse = Object | string;
interface FetchResponseMetadata {
bodyUsed: boolean;
contentType: null | string;
headers: Headers;
ok: boolean;
redirected: boolean;
response: FetchResponse;
status: number;
statusText: string;
url: string;
}
interface Options {
lifespan?: number;
metadata?: boolean;
}
interface OptionsWithMetadata extends Options {
metadata: true;
}
interface OptionsWithoutMetadata extends Options {
metadata?: false;
}
interface UseFetch {
(
input: RequestInfo,
init?: RequestInit | undefined,
options?: number | OptionsWithoutMetadata,
): FetchResponse;
(
input: RequestInfo,
init: RequestInit | undefined,
options: OptionsWithMetadata,
): FetchResponseMetadata;
}
const getDefaultFetchFunction = (): FetchFunction => {
if (typeof window === 'undefined') {
return (): Promise<Response> => {
return Promise.reject(
new Error('Cannot find `window`. Use `createUseFetch` to provide a custom `fetch` function.'),
);
};
}
if (typeof window.fetch === 'undefined') {
return (): Promise<Response> => {
return Promise.reject(
new Error('Cannot find `window.fetch`. Use `createUseFetch` to provide a custom `fetch` function.'),
);
};
}
return window.fetch;
};
const createUseFetch: CreateUseFetch = (
fetch: FetchFunction = getDefaultFetchFunction(),
): UseFetch => {
// Create a set of caches for this hook.
const caches: FetchCache[] = [];
function useFetch(
input: RequestInfo,
init?: RequestInit | undefined,
options?: number | OptionsWithoutMetadata,
): FetchResponse;
function useFetch(
input: RequestInfo,
init: RequestInit | undefined,
options: OptionsWithMetadata,
): FetchResponseMetadata;
function useFetch(
input: RequestInfo,
init?: RequestInit | undefined,
options: number | Options = 0,
): FetchResponse | FetchResponseMetadata {
if (typeof options === 'number') {
return useFetch(input, init, { lifespan: options });
}
const { metadata = false, lifespan = 0 } = options;
// Check each cache by this useFetch hook.
for (const cache of caches) {
// If this cache matches the request,
if (
deepEqual(input, cache.input) &&
deepEqual(init, cache.init)
) {
// If an error occurred, throw it so that componentDidCatch can handle
// it.
if (Object.prototype.hasOwnProperty.call(cache, 'error')) {
throw cache.error;
}
// If a response was successful, return it.
if (Object.prototype.hasOwnProperty.call(cache, 'response')) {
if (metadata) {
return {
bodyUsed: cache.bodyUsed,
contentType: cache.contentType,
headers: cache.headers,
ok: cache.ok,
redirected: cache.redirected,
response: cache.response,
status: cache.status,
statusText: cache.statusText,
url: cache.url,
};
}
return cache.response;
}
// If we are still waiting, throw the Promise so that Suspense can
// fallback.
throw cache.fetch;
}
}
// If no request in the cache matched this one, create a new cache entry.
const cache: FetchCache = {
// Make the fetch request.
fetch: fetch(input, init)
// Parse the response.
.then((response: Response): Promise<FetchResponse> => {
cache.contentType = response.headers.get('Content-Type');
if (metadata) {
cache.bodyUsed = response.bodyUsed;
cache.headers = response.headers;
cache.ok = response.ok;
cache.redirected = response.redirected;
cache.status = response.status;
cache.statusText = response.statusText;
}
if (
cache.contentType &&
cache.contentType.indexOf('application/json') !== -1
) {
return response.json();
}
return response.text();
})
// Cache the response.
.then((response: FetchResponse): void => {
cache.response = response;
})
// Handle an error.
.catch((e: Error): void => {
cache.error = e;
})
// Invalidate the cache.
.then((): void => {
if (lifespan > 0) {
setTimeout(
(): void => {
const index: number = caches.indexOf(cache);
if (index !== -1) {
caches.splice(index, 1);
}
},
lifespan,
);
}
}),
init,
input,
};
caches.push(cache);
throw cache.fetch;
}
return useFetch;
};
const _export: Export = Object.assign(
createUseFetch(), {
createUseFetch,
default: createUseFetch(),
});
export = _export;