cache-manager
's direct dependencies. Data on all dependencies, including transitive ones, is available via CSV download.Name | Version | Size | License | Type | Vulnerabilities |
---|---|---|---|---|---|
lodash.clonedeep | 4.5.0 | 11.36 kB | MIT | prod | |
lru-cache | 9.1.2 | 145.76 kB | ISC | prod |
Cache-manager is a popular npm package that serves as a flexible caching module for Node.js. It allows you to easily wrap functions in cache, implement tiered caches, and provides a consistent interface. It works with TypeScript and is compatible with ESModules. With cache-manager, data gets stored in each cache and fetched from the highest priority ones first. Effortlessly use any cache as long as it has the same API.
The cache-manager package can be used in many ways depending on your needs. Here are a few code examples for single and multi-store usage:
For a single store,
import { caching } from 'cache-manager';
const memoryCache = await caching('memory', {
max: 100,
ttl: 10 * 1000 /*milliseconds*/,
});
const ttl = 5 * 1000; /*milliseconds*/
await memoryCache.set('foo', 'bar', ttl);
console.log(await memoryCache.get('foo'));
// >> "bar"
await memoryCache.del('foo');
console.log(await memoryCache.get('foo'));
// >> undefined
const getUser = (id: string) => new Promise.resolve({ id: id, name: 'Bob' });
const userId = 123;
const key = 'user_' + userId;
console.log(await memoryCache.wrap(key, () => getUser(userId), ttl));
// >> { id: 123, name: 'Bob' }
For a multi-store,
import { multiCaching } from 'cache-manager';
const multiCache = multiCaching([memoryCache, someOtherCache]);
const userId2 = 456;
const key2 = 'user_' + userId;
const ttl = 5;
// Sets in all caches.
await multiCache.set('foo2', 'bar2', ttl);
// Fetches from highest priority cache that has the key.
console.log(await multiCache.get('foo2'));
// >> "bar2"
// Delete from all caches
await multiCache.del('foo2');
// Sets multiple keys in all caches.
// You can pass as many key, value tuples as you want
await multiCache.mset(
[
['foo', 'bar'],
['foo2', 'bar2'],
],
ttl
);
// mget() fetches from highest priority cache.
// If the first cache does not return all the keys,
// the next cache is fetched with the keys that were not found.
// This is done recursively until either:
// - all have been found
// - all caches has been fetched
console.log(await multiCache.mget('key', 'key2');
// >> ['bar', 'bar2']
// Delete keys with mdel() passing arguments...
await multiCache.mdel('foo', 'foo2');
The official documentation for cache-manager can be found in the README on its GitHub page. The examples and use cases listed there can provide an excellent guide to understand various functionalities and ways to use the cache-manager. Make sure to also check the unit test files named caching.test.ts
and multi-caching.test.ts
, and explore the official and third-party store engines for more cache options.