Created
January 30, 2023 02:19
-
-
Save miguelmota/2fb5d82022eab2126dce66a62acc1136 to your computer and use it in GitHub Desktop.
JavaScript pricefeed cache example
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
const cache: { | |
[tokenSymbol: string]: Promise<any> | |
} = {} | |
const cacheTimestamps: { | |
[tokenSymbol: string]: number | |
} = {} | |
class MyClass { | |
cacheTimeMs = 5 * 60 * 1000 | |
async getData (id: string, date: number) { | |
const cacheKey = `${id}:${date}` | |
if (cache[cacheKey] && cacheTimestamps[cacheKey]) { | |
const isRecent = cacheTimestamps[cacheKey] > Date.now() - this.cacheTimeMs | |
if (isRecent) { | |
return cache[cacheKey] | |
} | |
} | |
const promise = this._getData(tokenSymbol, days) | |
cache[cacheKey] = promise | |
cacheTimestamps[cacheKey] = Date.now() | |
return promise | |
} | |
async _getData (id: string, date: number) { | |
// ... | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment