Skip to content

Instantly share code, notes, and snippets.

@daino3
Created July 12, 2018 19:58
Show Gist options
  • Save daino3/ac8a21eb58a7f23c69b5284130fba9bb to your computer and use it in GitHub Desktop.
Save daino3/ac8a21eb58a7f23c69b5284130fba9bb to your computer and use it in GitHub Desktop.
+import moment from "moment/moment";
+
+//
+
+class CachedResource {
+ constructor(
+ cachedResourceKey,
+ cachedTimestampKey,
+ source,
+ dirtyFunc,
+ refreshFunc,
+ ) {
+ this.cachedResourceKey = cachedResourceKey;
+ this.cachedTimestampKey = cachedTimestampKey;
+ this.dirtyFunc = dirtyFunc;
+ this.refreshFunc = refreshFunc;
+ // must have get/set methods
+ this.source = source;
+ }
+
+ async getOrRefresh() {
+ // assume the cache is dirty
+ let isDirty = true;
+ let resource = this.source.get(this.cachedResourceKey);
+ const cachedLastUpdated = this.source.get(this.cachedTimestampKey);
+ const lastUpdatedResponse = await this.dirtyFunc().catch(console.error);
+ const lastUpdated = lastUpdatedResponse.data;
+
+ // compare 'cheap' API result based on timestamp
+ if (resource) {
+ isDirty = moment(lastUpdated['timestamp']).isAfter(moment(cachedLastUpdated));
+ }
+
+ // refresh if anything has changed
+ if (isDirty) {
+ const resourceResponse = await this.refreshFunc().catch(console.error);
+ resource = resourceResponse.data;
+ this.source.set(this.cachedResourceKey, resource);
+ this.source.set(this.cachedTimestampKey, lastUpdated['timestamp']);
+ return resource;
+ } else {
+ return resource;
+ }
+ }
+}
+
+
+export {CachedResource};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment