-
Notifications
You must be signed in to change notification settings - Fork 0
/
DataCache.js
35 lines (31 loc) · 932 Bytes
/
DataCache.js
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
export class DataCache {
constructor(fetchFunction, minutesToLive = 10) {
this.millisecondsToLive = minutesToLive * 60 * 1000;
this.fetchFunction = fetchFunction;
this.cache = null;
this.getData = this.getData.bind(this);
this.resetCache = this.resetCache.bind(this);
this.isCacheExpired = this.isCacheExpired.bind(this);
this.fetchDate = new Date(0);
}
isCacheExpired() {
return (this.fetchDate.getTime() + this.millisecondsToLive) < new Date().getTime();
}
getData() {
if (!this.cache || this.isCacheExpired()) {
console.log('expired - fetching new data');
return this.fetchFunction()
.then((data) => {
this.cache = data;
this.fetchDate = new Date();
return data;
});
} else {
console.log('cache hit');
return Promise.resolve(this.cache);
}
}
resetCache() {
this.fetchDate = new Date(0);
}
}