Last active
September 30, 2021 09:18
-
-
Save BananaAcid/a88800c38ae501d8871ef9aac1f8f6d8 to your computer and use it in GitHub Desktop.
simple, ugly and working (should probably be a class)
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
/* | |
* cache module for promise returns | |
* | |
* @author Nabil Redmann <repo+gist@bananaacid.de> | |
* @license ISC | |
* | |
* USE: | |
* cache.setTTL(10*1000); // optional | |
* | |
* let [ret1, ret2, ret3] = await cache.create( | |
* async() => await Promise.all([ | |
* async a => 1 | |
* ], false) | |
* ); | |
* | |
* cache.init(); // to reset | |
*/ | |
let cacheOpts = { | |
ttl: 10*1000, // secs | |
time: null, | |
data: [], | |
}; | |
let cache = {...cacheOpts, | |
...{ | |
init: (ttl) => cache = {...cache, ...cacheOpts, ...(ttl !== undefined ? {ttl} : {})}, | |
setTTL: ttl => cache.ttl = ttl, | |
create: async (retProm, enforce) => { | |
if (enforce || (cache.time <= +(new Date))) { | |
cache.time = +(new Date) + cache.ttl; | |
// console.log('CACHE refresh', {ttl: cache.ttl, next_time: cache.time, now: +(new Date)}); | |
cache.data = await retProm(); | |
} | |
return cache.data; | |
}, | |
isValid: _ => (cache.time > +(new Date)), | |
get: pos => cache.data[pos], | |
getAll: _ => cache.data, | |
has: pos => !!cache.data[pos] | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment