Created
February 22, 2021 10:23
-
-
Save diversemix/66ce4c051d81fad082c2a87145b48d5d to your computer and use it in GitHub Desktop.
Cache
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment