ITP Express Redis Cache
A light api route cache system with Redis for Express.js
Installation
npm install itp-express-redis-cache
Usage
const express = require('express');
const app = express();
const ITPExpressRedisCache = require('itp-express-redis-cache')();
app.get('/', ITPExpressRedisCache.route(), (req, res) => {
res.json({ foo: 'bar' });
});
app.listen(3000, () => {
console.log('Example app listening on port 3000!');
});
Options
Init options:
const ITPExpressRedisCache = require('itp-express-redis-cache')({
port: 6379,
host: 'localhost',
authPass: null,
prefix: 'my-sample-app',
enabled: true,
excludeStatuscodes: 500,
});
The excludeStatuscodes parameter can also be an array:
const ITPExpressRedisCache = require('itp-express-redis-cache')({
port: 6379,
host: 'localhost',
authPass: null,
prefix: 'my-sample-app',
enabled: true,
excludeStatuscodes: [404, 406, 408, 410],
});
Route middleware options:
ITPExpressRedisCache.route({
key: 'custom-redis-key-for-route',
expire: 120,
})
The route key parameter can also be a function:
ITPExpressRedisCache.route({
key: (req) => `custom-key:${req.originalUrl}`,
expire: 120,
})
The expire parameter can also be a function:
ITPExpressRedisCache.route({
key: (req) => `custom-key:${req.originalUrl}`,
expire: (req) => 120 + 4,
})
Application-level middleware
Simply use app.use
of express to use ITPExpressRedisCache
as an Application-level middleware.
app.use(ITPExpressRedisCache.route())
Disable Caching inside the Route
You can disable caching for specific routes by adding res.skipCache = true
to opt out the route from getting cached.
app.get('/:paramKey', (req, res) => {
res.skipCache = paramKey === 1300;
res.send('Hello');
});
Supported env variables
- REDIS_HOST
- REDIS_PORT
- REDIS_PASS
License
ITP-Express-Redis-Cache is freely distributable under the terms of the MIT license.