@impactor/cache
v3.0.4
Published
a cache system, supporting any cache location
Readme
A cache system.
Example
let data = await cache(
// list of cache files to validate
// the first valid cache file in order will be considered
["./report-today.json", "./report-yesterday.json"],
// an optional data source to fetch the fresh cache data in case of no valid cache file is found
() => fetch("https://my-server.com/getReport"),
{
// the maximum time period before considering a file as expired.
maxAge: 1000,
// a fallback to be used in case of the dataSource function failed to refresh the cache.
// in this case, it accepts a recently expired cache
maxStale: 2000,
// a callback that is called to read the cache value
// it may read from file system, memory, database, or any other source.
// in real-life usage, you may need to iterate over all entries to find the first cache hit.
read: (entries) => readFile(`./cache/${entries[0]}`),
// a callback that is called if all cache sources are expired,
// and the dataSource retrieved the fresh data successfully.
write: (entry, data) => writeFile(`./cache/${entry}`, JSON.stringify(data)),
},
);If you plan to save the cached data in file-system, check out cacheFS()
