1 import * as express from 'express'
2 import * as AsyncLock from 'async-lock'
3 import { parseDurationToMs } 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 const lifetime = parseDurationToMs(lifetimeArg)
12 return async function (req: express.Request, res: express.Response, next: express.NextFunction) {
13 const redisKey = Redis.Instance.generateCachedRouteKey(req)
16 await lock.acquire(redisKey, async (done) => {
17 const cached = await Redis.Instance.getCachedRoute(req)
21 logger.debug('No cached results for route %s.', req.originalUrl)
23 const sendSave = res.send.bind(res)
24 const redirectSave = res.redirect.bind(res)
26 res.send = (body) => {
27 if (res.statusCode >= 200 && res.statusCode < 400) {
28 const contentType = res.get('content-type')
30 Redis.Instance.setCachedRoute(req, body, lifetime, contentType, res.statusCode)
33 logger.error('Cannot cache route.', { err })
43 res.redirect = url => {
46 return redirectSave(url)
52 if (cached.contentType) res.set('content-type', cached.contentType)
54 if (cached.statusCode) {
55 const statusCode = parseInt(cached.statusCode, 10)
56 if (!isNaN(statusCode)) res.status(statusCode)
59 logger.debug('Use cached result for %s.', req.originalUrl)
60 res.send(cached.body).end()
65 logger.error('Cannot serve cached route.', { err })
71 // ---------------------------------------------------------------------------