-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
48 lines (39 loc) · 1.19 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
class MemoPromise {
cache: {};
getPromise: () => any;
constructor(getPromise: any) {
this.cache = {};
this.getPromise = getPromise;
this.request = this.request.bind(this);
}
/** Creates a Promise and associates an uniqueId to it, stored in a temporary
* cache. Preventing two equal promises to be requested, while the uniqueId
* is valid. */
request(uniqueKey: string) {
if (!uniqueKey) {
throw new Error('Unique key is not passed');
}
if (window.localStorage.getItem(uniqueKey) === 'used') {
return this.cache[uniqueKey];
}
if (this.cache[uniqueKey]) {
return this.cache[uniqueKey];
}
window.localStorage.setItem(uniqueKey, 'used');
const promise = this.getPromise;
this.cache[uniqueKey] = promise;
return this.cache[uniqueKey];
}
deleteCache(key: string) {
localStorage.removeItem(key);
delete this.cache[key];
}
requestId = (url: string, load: any) => {
const timestamp = Date.now()
.toString()
.substr(0, 8);
const loadString = JSON.stringify(load);
return `${url}-${loadString}-${timestamp}`;
};
}
export default MemoPromise;