await-cache
A cache for async-functions. It also works for non-async functions. It's even possible to enable a LRU-algorithm.
How to install
npm i await-cache
How to use
Simply surround the async function you want to cache. In this example fetch is a function that loads a file.
const cachify = require('await-cache');
const cachedFetch = cachify(fetch, 1000 * 60 * 60)
async function test() {
try {
const data1 = await cachedFetch('foo.bar')
const data2 = await cachedFetch('foo.bar')
const data3 = await cachedFetch('foo2.bar')
} catch(e) {
console.error(e)
}
}
Second argument can be the cache-time in milliseconds or an object of options. With setting the maxSize-option you enable the LRU-Cache:
const cachify = require('await-cache');
const cachedFunc = cachify(async (filename) => {
let data = await fetch(filename)
return JSON.parse(data)
}, {
maxAge: 60 * 60 * 1000,
maxSize: 2,
serialize: (args) => JSON.stringify(args)
})
The default serialisation for the arguments uses JSON.stringify. So you will have to write a custom serialisation if you want to use functions or complex objects as arguments.
License
MIT