1 import * as express from 'express'
2 import * as AsyncLock from 'async-lock'
3 import { parseDuration } from '../helpers/core-utils'
4 import { Redis } from '../lib/redis'
5 import { logger } from '../helpers/logger'
7 const lock = new AsyncLock({ timeout: 5000 })
9 function cacheRoute (lifetimeArg: string | number) {
10 return async function (req: express.Request, res: express.Response, next: express.NextFunction) {
11 const redisKey = Redis.Instance.buildCachedRouteKey(req)
14 await lock.acquire(redisKey, async (done) => {
15 const cached = await Redis.Instance.getCachedRoute(req)
19 logger.debug('No cached results for route %s.', req.originalUrl)
21 const sendSave = res.send.bind(res)
23 res.send = (body) => {
24 if (res.statusCode >= 200 && res.statusCode < 400) {
25 const contentType = res.get('content-type')
26 const lifetime = parseDuration(lifetimeArg)
28 Redis.Instance.setCachedRoute(req, body, lifetime, contentType, res.statusCode)
31 logger.error('Cannot cache route.', { err })
42 if (cached.contentType) res.set('content-type', cached.contentType)
44 if (cached.statusCode) {
45 const statusCode = parseInt(cached.statusCode, 10)
46 if (!isNaN(statusCode)) res.status(statusCode)
49 logger.debug('Use cached result for %s.', req.originalUrl)
50 res.send(cached.body).end()
55 logger.error('Cannot serve cached route.', err)
61 // ---------------------------------------------------------------------------