1 import * as express from 'express'
2 import * as AsyncLock from 'async-lock'
3 import { Redis } from '../lib/redis'
4 import { logger } from '../helpers/logger'
6 const lock = new AsyncLock({ timeout: 5000 })
8 function cacheRoute (lifetime: number) {
9 return async function (req: express.Request, res: express.Response, next: express.NextFunction) {
10 const redisKey = Redis.Instance.buildCachedRouteKey(req)
12 await lock.acquire(redisKey, async (done) => {
13 const cached = await Redis.Instance.getCachedRoute(req)
17 logger.debug('Not cached result for route %s.', req.originalUrl)
19 const sendSave = res.send.bind(res)
21 res.send = (body) => {
22 if (res.statusCode >= 200 && res.statusCode < 400) {
23 const contentType = res.getHeader('content-type').toString()
24 Redis.Instance.setCachedRoute(req, body, lifetime, contentType, res.statusCode)
27 logger.error('Cannot cache route.', { err })
38 if (cached.contentType) res.contentType(cached.contentType)
40 if (cached.statusCode) {
41 const statusCode = parseInt(cached.statusCode, 10)
42 if (!isNaN(statusCode)) res.status(statusCode)
45 logger.debug('Use cached result for %s.', req.originalUrl)
46 res.send(cached.body).end()
53 // ---------------------------------------------------------------------------