1 import * as express from 'express'
2 import { Redis } from '../lib/redis'
3 import { logger } from '../helpers/logger'
5 function cacheRoute (lifetime: number) {
6 return async function (req: express.Request, res: express.Response, next: express.NextFunction) {
7 const cached = await Redis.Instance.getCachedRoute(req)
11 logger.debug('Not cached result for route %s.', req.originalUrl)
13 const sendSave = res.send.bind(res)
15 res.send = (body) => {
16 if (res.statusCode >= 200 && res.statusCode < 400) {
17 const contentType = res.getHeader('content-type').toString()
18 Redis.Instance.setCachedRoute(req, body, lifetime, contentType, res.statusCode)
19 .catch(err => logger.error('Cannot cache route.', { err }))
28 if (cached.contentType) res.contentType(cached.contentType)
30 if (cached.statusCode) {
31 const statusCode = parseInt(cached.statusCode, 10)
32 if (!isNaN(statusCode)) res.status(statusCode)
35 logger.debug('Use cached result for %s.', req.originalUrl)
36 return res.send(cached.body).end()
40 // ---------------------------------------------------------------------------