Skip to content

Instantly share code, notes, and snippets.

@diversemix
Created February 22, 2021 10:23
Show Gist options
  • Save diversemix/66ce4c051d81fad082c2a87145b48d5d to your computer and use it in GitHub Desktop.
Save diversemix/66ce4c051d81fad082c2a87145b48d5d to your computer and use it in GitHub Desktop.
Cache
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