Introduction to Cache-manager
The cache-manager
library is a powerful caching module for Node.js applications, allowing developers to implement various cache strategies seamlessly. In this comprehensive guide, we’ll explore a rich set of APIs provided by cache-manager
with practical examples and a full-fledged application demonstrating its usage.
Basic Setup
const cacheManager = require('cache-manager');
const memoryCache = cacheManager.caching({ store: 'memory', max: 100, ttl: 10 /*seconds*/ });
memoryCache.set('foo', 'bar', { ttl: 5 }, (err) => {
if (err) throw err;
console.log('cached foo/bar');
});
memoryCache.get('foo', (err, result) => {
if (err) throw err;
console.log(result); // bar
});
Multiple Stores
const redisStore = require('cache-manager-redis-store');
const multiCache = cacheManager.multiCaching([memoryCache, cacheManager.caching({
store: redisStore,
host: 'localhost', port: 6379, db: 0, ttl: 600
})]);
multiCache.set('foo', 'bar', (err) => {
if (err) throw err;
console.log('Value cached in multiple stores');
});
multiCache.get('foo', (err, result) => {
if (err) throw err;
console.log(result);
});
API Examples
Setting Cache
memoryCache.set('key1', 'value1', { ttl: 10 }, (err) => {
if (err) throw err;
});
Getting Cache
memoryCache.get('key1', (err, result) => {
if (err) throw err;
console.log(result);
});
Del Cache
memoryCache.del('key1', (err) => {
if (err) throw err;
});
Wrapping Cache
function fetchData(id, cb) {
// Simulate fetching data
setTimeout(() => cb(null, { id, data: 'Sample data' }), 1000);
}
memoryCache.wrap('data-id', (cb) => fetchData(1, cb), { ttl: 30 }, (err, result) => {
if (err) throw err;
console.log(result);
});
App Example Using cache-manager
const express = require('express');
const cacheManager = require('cache-manager');
const app = express();
const port = 3000;
const memoryCache = cacheManager.caching({ store: 'memory', max: 100, ttl: 10 /*seconds*/ });
function fetchUser(id) {
// Simulate database access
return new Promise((resolve) => setTimeout(() => resolve({ id, name: 'User' + id }), 2000));
}
app.get('/user/:id', async (req, res) => {
const userId = req.params.id;
memoryCache.wrap(userId, () => fetchUser(userId), { ttl: 10 })
.then(result => res.json(result))
.catch(err => res.status(500).send(err));
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});
With these powerful APIs at your disposal, implementing efficient caching in your Node.js applications using cache-manager
is a breeze!
Hash: 790255aefc7ac043e79aa38af3fc4a759b400e025e6f9ad1316f2ac33c689a75