forked from solidjs-community/solid-primitives
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
305 lines (291 loc) · 10.2 KB
/
index.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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
import {
createMemo,
createSignal,
type Accessor,
type ResourceFetcher,
type ResourceFetcherInfo,
type Signal,
onCleanup,
} from "solid-js";
import { createStore, reconcile, unwrap } from "solid-js/store";
export type AbortableOptions = {
noAutoAbort?: boolean;
timeout?: number;
};
/**
* **Creates and handles an AbortSignal**
* ```ts
* const [signal, abort, filterAbortError] =
* makeAbortable({ timeout: 10000 });
* const fetcher = (url) => fetch(url, { signal: signal() })
* .catch(filterAbortError); // filters abort errors
* ```
* Returns an accessor for the signal and the abort callback.
*
* Options are optional and include:
* - `timeout`: time in Milliseconds after which the fetcher aborts automatically
* - `noAutoAbort`: can be set to true to make a new source not automatically abort a previous request
*/
export function makeAbortable(
options: AbortableOptions = {},
): [
signal: () => AbortSignal,
abort: (reason?: string) => void,
filterAbortError: (err: any) => void,
] {
let controller: AbortController | undefined;
let timeout: NodeJS.Timeout | number | undefined;
const abort = (reason?: string) => {
timeout && clearTimeout(timeout);
controller?.abort(reason);
};
const signal = () => {
if (!options.noAutoAbort && controller?.signal.aborted === false) {
abort("retry");
}
controller = new AbortController();
if (options.timeout) {
timeout = setTimeout(() => abort("timeout"), options.timeout);
}
return controller.signal;
};
return [
signal,
abort,
err => {
if (err.name === "AbortError") {
return undefined;
}
throw err;
},
];
}
/**
* **Creates and handles an AbortSignal with automated cleanup**
* ```ts
* const [signal, abort, filterAbortError] =
* createAbortable();
* const fetcher = (url) => fetch(url, { signal: signal() })
* .catch(filterAbortError); // filters abort errors
* ```
* Returns an accessor for the signal and the abort callback.
*
* Options are optional and include:
* - `timeout`: time in Milliseconds after which the fetcher aborts automatically
* - `noAutoAbort`: can be set to true to make a new source not automatically abort a previous request
*/
export function createAbortable(options?: AbortableOptions) {
const [signal, abort, filterAbortError] = makeAbortable(options);
onCleanup(abort);
return [signal, abort, filterAbortError];
}
const mapEntries = (entries: [key: string, value: any][]) =>
entries.map(entry => entry.map(serializer).join(":"));
export const serializer = (req: any): string =>
// non-objects and null allow for string coercion
!req || typeof req !== "object"
? req + "" === req
? `"${req}"`
: req + ""
: // serializing the array items allows for string coercion: [1,2,3] == "[1,2,3]"
Array.isArray(req)
? `[${req.map(serializer)}]`
: // Headers and maps support an entries method giving an entries iterator,
// otherwise use Object.entries()s
`{${mapEntries(
typeof req.entries === "function" ? [...req.entries()] : Object.entries(req),
)}}`;
export type CacheEntry<T, S> = {
source: S;
data: T;
ts: number;
};
export const cache: Record<string, CacheEntry<any, any>> = {};
export type CacheOptions<T, S> = {
cache?: Record<string, CacheEntry<T, S>>;
expires?: number | ((entry: Omit<CacheEntry<T, S>, "ts">) => number);
serialize?: [(input: any) => string, (input: string) => any];
sourceHash?: (source: S) => string;
storage?: Storage;
storageKey?: string;
};
/**
* **Creates a caching fetcher**
* ```ts
* const [fetcher, invalidate, expired] =
* makeCache(
* (source) => fetch(source).then(r => r.json()),
* { storage: localStorage, storageKey: 'foo' }
* );
* ```
* Wraps the fetcher to use a cache. Returns the wrapped fetcher, an invalidate callback that requires the source to invalidate the request and a signal accessor with the last automatically invalidated request.
*
* Can be customized with the following optional options:
* - `cache` - allows to use a local cache instead of the global one, of type `Record<string, CacheEntry<T, S>>`
* - `expires` - allows to define a custom timeout; either accepts a number or a function that receives an object with source and data of the request and returns a number in Milliseconds
* - `serialize` - a tuple [serialize, deserialize] used for persistence, default is `[JSON.stringify, JSON.parse]`
* - `sourceHash` - a function receiving the source (true if none is used) and returns a hash string
* - `storage` - a storage like localStorage to persist the cache over reloads
* - `storageKey` - the key which is used to store the cache in the storage
*/
export function makeCache<T, S, R>(
fetcher: ResourceFetcher<S, T, R>,
options?: CacheOptions<T, S>,
): [
fetcher: ResourceFetcher<S, T, R>,
invalidate: ((source?: S) => void) & { all: () => void },
expired: Accessor<CacheEntry<T, S> | undefined>,
] {
const [expired, setExpired] = createSignal<CacheEntry<T, S>>();
const [serialize, deserialize] = options?.serialize || [JSON.stringify, JSON.parse];
const localCache = options?.cache || (cache as Record<string, CacheEntry<T, S>>);
const key = options?.storageKey || "solid-cache";
const save = () => {
try {
options?.storage?.setItem(key, serialize(localCache));
} catch (_) {
/**/
}
};
const expireTimeout =
typeof options?.expires === "function"
? options.expires
: () => (options?.expires as number | undefined) || 300000;
if (options?.storage) {
try {
Object.assign(localCache, deserialize(options.storage.getItem(key) || "{}"));
} catch (_) {
/**/
}
}
const sourceHash = options?.sourceHash || serializer;
return [
async (s: S, info: ResourceFetcherInfo<T, R>) => {
const hash = sourceHash(s);
const cachedEntry: CacheEntry<T, S> | undefined = Object.hasOwn(localCache, hash)
? localCache[hash]
: undefined;
const now = +new Date();
if (cachedEntry && (cachedEntry.ts || now) >= now) {
return cachedEntry.data;
}
const response: T = await fetcher(s, info);
const entry = { source: s, data: response } as CacheEntry<T, S>;
const expiryDelay = expireTimeout(entry);
entry.ts = now + expiryDelay;
localCache[hash] = entry;
save();
setTimeout(() => {
if (Object.hasOwn(localCache, hash)) {
delete localCache[hash];
save();
setExpired(entry);
}
}, expiryDelay);
return response;
},
Object.assign(
(s: S = true as S) => {
delete localCache[sourceHash(s)];
save();
},
{
all: () => {
Object.keys(localCache).forEach(key => {
delete localCache[key];
});
save();
},
},
),
expired,
];
}
export type RetryOptions = {
delay?: number;
retries?: number;
};
/**
* **Creates a fetcher that retries multiple times in case of errors**
* ```ts
* const fetcher = makeRetrying((url) => fetch(url), { retries: 5 });
* ```
* Receives the fetcher and an optional options object and returns a wrapped fetcher that retries on error after a delay multiple times.
*
* The optional options object contains the following optional properties:
* - `delay` - number of Milliseconds to wait before retrying; default is 5s
* - `retries` - number of times a request should be repeated before giving up throwing the last error; default is 3 times
*/
export function makeRetrying<S, T, R = unknown>(
fetcher: ResourceFetcher<S, T, R>,
options: RetryOptions = {},
): ResourceFetcher<S, T, R> {
const delay = options.delay ?? 5000;
let retries = options.retries || 3;
const retrying: ResourceFetcher<S, T, R> = async (k: S, info: ResourceFetcherInfo<T, R>) => {
try {
return await fetcher(k, info);
} catch (error: unknown) {
if (retries-- > 0) {
delay && (await new Promise(resolve => setTimeout(resolve, delay)));
return retrying(k, info);
} else {
retries = options.retries || 3;
throw error;
}
}
};
return retrying;
}
function toArray(item: any) {
return Array.isArray(item) ? item : item ? [item] : [];
}
/**
* **Automatically aggregates resource changes**
* ```ts
* const pages = makeAggregated(currentPage, []);
* ```
* Depending on the content of the initialValue or the first response, this will aggregate the incoming responses:
* - null will not overwrite undefined
* - if the previous value is an Array, incoming values will be appended
* - if any of the values are Objects, the current one will be shallow-merged into the previous one
* - if the previous value is a string, more string data will be appended
* - otherwise the incoming data will be put into an array
*
* Objects and Arrays are re-created on each operation, but the values will be left untouched, so `<For>` should work fine.
*/
export function createAggregated<R, I extends R | R[]>(res: Accessor<R>, initialValue?: I) {
return createMemo<I | R | {} | R[] | I[] | undefined>(previous => {
const current = res();
return current == null && previous == null
? previous
: Array.isArray(previous || current)
? [...toArray(previous), ...toArray(current)]
: typeof (previous || current) === "object"
? { ...previous, ...current }
: typeof previous === "string" || typeof current === "string"
? (previous?.toString() || "") + (current || "")
: previous
? [previous, current]
: [current];
}, initialValue);
}
/**
* **Creates a store-based signal for fine-grained resources**
* ```ts
* const [data] = createResource(fetcher, { storage, createDeepSignal });
* ```
* @see https://www.solidjs.com/docs/latest/api#createresource:~:text=Resources%20can%20be%20set%20with%20custom%20defined%20storage
*/
export function createDeepSignal<T>(): Signal<T | undefined>;
export function createDeepSignal<T>(value: T): Signal<T>;
export function createDeepSignal<T>(v?: T): Signal<T> {
const [store, setStore] = createStore([v]);
return [
() => store[0],
(update: T) => (
setStore(0, reconcile(typeof update === "function" ? update(unwrap(store[0])) : update)),
store[0]
),
] as Signal<T>;
}