-
Notifications
You must be signed in to change notification settings - Fork 463
/
Copy pathcache.ts
48 lines (41 loc) · 1.15 KB
/
cache.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
import { pipe, subscribe } from 'wonka';
import type { Client, OperationResult } from '@urql/core';
type CacheEntry = OperationResult | Promise<unknown> | undefined;
interface Cache {
get(key: number): CacheEntry;
set(key: number, value: CacheEntry): void;
dispose(key: number): void;
}
interface ClientWithCache extends Client {
_react?: Cache;
}
export const getCacheForClient = (client: Client): Cache => {
if (!(client as ClientWithCache)._react) {
const reclaim = new Set();
const map = new Map<number, CacheEntry>();
if (client.operations$ /* not available in mocks */) {
pipe(
client.operations$,
subscribe(operation => {
if (operation.kind === 'teardown' && reclaim.has(operation.key)) {
reclaim.delete(operation.key);
map.delete(operation.key);
}
})
);
}
(client as ClientWithCache)._react = {
get(key) {
return map.get(key);
},
set(key, value) {
reclaim.delete(key);
map.set(key, value);
},
dispose(key) {
reclaim.add(key);
},
};
}
return (client as ClientWithCache)._react!;
};