Skip to content

Instantly share code, notes, and snippets.

@BananaAcid
Last active September 30, 2021 09:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BananaAcid/a88800c38ae501d8871ef9aac1f8f6d8 to your computer and use it in GitHub Desktop.
Save BananaAcid/a88800c38ae501d8871ef9aac1f8f6d8 to your computer and use it in GitHub Desktop.
simple, ugly and working (should probably be a class)
/*
* 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