app2-api/middlewares/cache.js

28 lines
797 B
JavaScript
Raw Normal View History

2019-07-24 21:03:10 +00:00
const apicache = require('apicache');
const redis = require('redis');
2019-09-03 15:40:13 +00:00
const config = require('../config');
2019-07-24 21:03:10 +00:00
2019-07-28 20:08:15 +00:00
const cacheWithRedis = apicache
.options({
2019-09-03 15:40:13 +00:00
debug: config.cache.debug,
defaultDuration: config.cache.defaultDuration,
enabled: config.cache.enabled,
2019-07-28 20:08:15 +00:00
//redisClient: redis.createClient(),
//appendKey: (req, res) => req.user ? req.user.id : '',
});
const cacheMiddleware = cacheWithRedis.middleware;
2019-07-24 21:03:10 +00:00
// higher-order function returns false for responses of other status codes (e.g. 403, 404, 500, etc)
const onlyStatus200 = (req, res) => res.statusCode === 200
2019-07-28 20:08:15 +00:00
const cacheSuccesses = (time) => { return cacheMiddleware(time, onlyStatus200) };
2019-07-24 21:03:10 +00:00
module.exports = {
2019-07-28 20:08:15 +00:00
apicache: cacheWithRedis,
cacheMiddleware,
2019-07-24 21:03:10 +00:00
cacheSuccesses,
}