UNPKG

2.52 kBJavaScriptView Raw
1import { mutate } from './use-swr';
2import hash from './libs/hash';
3export default class Cache {
4 constructor(initialData = {}) {
5 this.__cache = new Map(Object.entries(initialData));
6 this.__listeners = [];
7 }
8 get(key) {
9 const [_key] = this.serializeKey(key);
10 return this.__cache.get(_key);
11 }
12 set(key, value, shouldNotify = true) {
13 const [_key] = this.serializeKey(key);
14 this.__cache.set(_key, value);
15 if (shouldNotify)
16 mutate(key, value, false);
17 this.notify();
18 }
19 keys() {
20 return Array.from(this.__cache.keys());
21 }
22 has(key) {
23 const [_key] = this.serializeKey(key);
24 return this.__cache.has(_key);
25 }
26 clear(shouldNotify = true) {
27 if (shouldNotify)
28 this.__cache.forEach(key => mutate(key, null, false));
29 this.__cache.clear();
30 this.notify();
31 }
32 delete(key, shouldNotify = true) {
33 const [_key] = this.serializeKey(key);
34 if (shouldNotify)
35 mutate(key, null, false);
36 this.__cache.delete(_key);
37 this.notify();
38 }
39 // TODO: introduce namespace for the cache
40 serializeKey(key) {
41 let args = null;
42 if (typeof key === 'function') {
43 try {
44 key = key();
45 }
46 catch (err) {
47 // dependencies not ready
48 key = '';
49 }
50 }
51 if (Array.isArray(key)) {
52 // args array
53 args = key;
54 key = hash(key);
55 }
56 else {
57 // convert null to ''
58 key = String(key || '');
59 }
60 const errorKey = key ? 'err@' + key : '';
61 return [key, args, errorKey];
62 }
63 subscribe(listener) {
64 if (typeof listener !== 'function') {
65 throw new Error('Expected the listener to be a function.');
66 }
67 let isSubscribed = true;
68 this.__listeners.push(listener);
69 return () => {
70 if (!isSubscribed)
71 return;
72 isSubscribed = false;
73 const index = this.__listeners.indexOf(listener);
74 if (index > -1) {
75 this.__listeners[index] = this.__listeners[this.__listeners.length - 1];
76 this.__listeners.length--;
77 }
78 };
79 }
80 // Notify Cache subscribers about a change in the cache
81 notify() {
82 for (let listener of this.__listeners) {
83 listener();
84 }
85 }
86}