Created
July 12, 2018 19:58
-
-
Save daino3/ac8a21eb58a7f23c69b5284130fba9bb to your computer and use it in GitHub Desktop.
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
+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