Skip to content

Instantly share code, notes, and snippets.

@miguelmota
Created January 30, 2023 02:19
Show Gist options
  • Save miguelmota/2fb5d82022eab2126dce66a62acc1136 to your computer and use it in GitHub Desktop.
Save miguelmota/2fb5d82022eab2126dce66a62acc1136 to your computer and use it in GitHub Desktop.
JavaScript pricefeed cache example
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