-
Notifications
You must be signed in to change notification settings - Fork 169
/
data.ts
196 lines (182 loc) · 6.34 KB
/
data.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
import { useCallback, useContext, useEffect, useMemo, useState } from "react";
import { FetchError } from "../../lib/helpers.ts";
import { DataContext } from "./context.ts";
export type HttpMethod = "get" | "post" | "put" | "patch" | "delete";
export type UpdateStrategy<T> = "none" | "replace" | {
optimisticUpdate?: (data: T) => T;
onFailure?: (error: Error) => void;
replace?: boolean;
};
export const useData = <T = unknown>(): {
data: T;
isMutating: HttpMethod | boolean;
mutation: typeof mutation;
reload: (signal?: AbortSignal) => Promise<void>;
} => {
const { dataUrl, dataCache } = useContext(DataContext);
const [data, setData] = useState(() => {
const cached = dataCache.get(dataUrl);
if (cached) {
if (typeof cached.data === "function") {
const data = cached.data();
if (data instanceof Promise) {
throw data.then((data) => {
cached.data = data;
return data;
});
}
throw new Error(`Data for ${dataUrl} has invalid type [function].`);
}
return cached.data as T;
}
throw new Error(`Data for ${dataUrl} is not found`);
});
const [isMutating, setIsMutating] = useState<HttpMethod | boolean>(false);
const action = useCallback(async (method: HttpMethod, fetcher: Promise<Response>, update: UpdateStrategy<T>) => {
const updateIsObject = update && typeof update === "object" && update !== null;
const optimistic = updateIsObject && typeof update.optimisticUpdate === "function";
const replace = update === "replace" || (updateIsObject && !!update.replace);
setIsMutating(method);
let rollbackData: T | undefined = undefined;
if (optimistic) {
const optimisticUpdate = update.optimisticUpdate!;
setData((prev) => {
if (prev !== undefined) {
rollbackData = prev;
return optimisticUpdate(clone(prev));
}
return prev;
});
}
const res = await fetcher;
if (res.status >= 400) {
if (optimistic) {
if (rollbackData !== undefined) {
setData(rollbackData);
}
if (update.onFailure) {
update.onFailure(await FetchError.fromResponse(res));
}
}
setIsMutating(false);
return res;
}
if (res.status >= 300) {
const redirectUrl = res.headers.get("Location");
if (redirectUrl) {
location.href = new URL(redirectUrl, location.href).href;
}
if (optimistic && rollbackData !== undefined) {
setData(rollbackData);
}
setIsMutating(false);
return res;
}
if (replace && res.ok) {
try {
const data = await res.json();
const dataCacheTtl = dataCache.get(dataUrl)?.dataCacheTtl;
dataCache.set(dataUrl, { data, dataCacheTtl, dataExpires: Date.now() + (dataCacheTtl || 1) * 1000 });
setData(data);
} catch (_) {
if (optimistic) {
if (rollbackData !== undefined) {
setData(rollbackData);
}
if (update.onFailure) {
update.onFailure(new FetchError(500, {}, "Data must be valid JSON"));
}
}
}
}
setIsMutating(false);
return res;
}, [dataUrl]);
const reload = useCallback(async (signal?: AbortSignal) => {
try {
const res = await fetch(dataUrl, { headers: { "Accept": "application/json" }, signal, redirect: "manual" });
if (res.status >= 400) {
throw await FetchError.fromResponse(res);
}
if (res.status >= 300) {
const redirectUrl = res.headers.get("Location");
if (redirectUrl) {
location.href = redirectUrl;
}
throw new FetchError(500, {}, "Missing the `Location` header");
}
if (res.ok) {
const data = await res.json();
const cc = res.headers.get("Cache-Control");
const dataCacheTtl = cc && cc.includes("max-age=") ? parseInt(cc.split("max-age=")[1]) : undefined;
const dataExpires = Date.now() + (dataCacheTtl || 1) * 1000;
dataCache.set(dataUrl, { data, dataExpires });
setData(data);
} else {
throw new FetchError(500, {}, "Data must be valid JSON");
}
} catch (error) {
throw error;
}
}, [dataUrl]);
const mutation = useMemo(() => {
return {
post: (data?: unknown, update?: UpdateStrategy<T>) => {
return action("post", send("post", dataUrl, data), update ?? "none");
},
put: (data?: unknown, update?: UpdateStrategy<T>) => {
return action("put", send("put", dataUrl, data), update ?? "none");
},
patch: (data?: unknown, update?: UpdateStrategy<T>) => {
return action("patch", send("patch", dataUrl, data), update ?? "none");
},
delete: (data?: unknown, update?: UpdateStrategy<T>) => {
return action("delete", send("delete", dataUrl, data), update ?? "none");
},
};
}, [dataUrl]);
useEffect(() => {
const now = Date.now();
const cache = dataCache.get(dataUrl);
let ac: AbortController | null = null;
if (cache === undefined || cache.dataExpires === undefined || cache.dataExpires < now) {
ac = new AbortController();
reload(ac.signal).finally(() => {
ac = null;
});
} else if (cache.data !== undefined) {
setData(cache.data as never);
}
return () => ac?.abort();
}, [dataUrl]);
return { data, isMutating, mutation, reload };
};
function send(method: HttpMethod, href: string, data: unknown) {
let body: BodyInit | undefined;
const headers = new Headers();
if (typeof data === "string") {
body = data;
} else if (typeof data === "number") {
body = data.toString();
} else if (typeof data === "object") {
if (data instanceof ArrayBuffer || data instanceof Uint8Array) {
body = data;
} else if (data instanceof FormData) {
body = data;
} else if (data instanceof URLSearchParams) {
body = data;
} else if (data instanceof Blob) {
body = data;
headers.append("Content-Type", data.type);
} else {
body = JSON.stringify(data);
headers.append("Content-Type", "application/json; charset=utf-8");
}
}
return fetch(href, { method, body, headers, redirect: "manual" });
}
function clone<T>(obj: T): T {
// deno-lint-ignore ban-ts-comment
// @ts-ignore
return typeof structuredClone === "function" ? structuredClone(obj) : JSON.parse(JSON.stringify(obj));
}