1 import * as express from 'express'
2 import * as AsyncLock from 'async-lock'
3 import { parseDuration } from '../helpers/utils'
4 import { Redis } from '../lib/redis'
5 import { logger } from '../helpers/logger'
7 const lock = new AsyncLock({ timeout: 5000 })
9 function cacheRoute (lifetime: number) {
10 return async function (req: express.Request, res: express.Response, next: express.NextFunction) {
11 const redisKey = Redis.Instance.buildCachedRouteKey(req)
13 await lock.acquire(redisKey, async (done) => {
14 const cached = await Redis.Instance.getCachedRoute(req)
18 logger.debug('No cached results for route %s.', req.originalUrl)
20 const sendSave = res.send.bind(res)
22 res.send = (body) => {
23 if (res.statusCode >= 200 && res.statusCode < 400) {
24 const contentType = res.get('content-type')
25 Redis.Instance.setCachedRoute(req, body, lifetime, contentType, res.statusCode)
28 logger.error('Cannot cache route.', { err })
39 if (cached.contentType) res.set('content-type', cached.contentType)
41 if (cached.statusCode) {
42 const statusCode = parseInt(cached.statusCode, 10)
43 if (!isNaN(statusCode)) res.status(statusCode)
46 logger.debug('Use cached result for %s.', req.originalUrl)
47 res.send(cached.body).end()
54 const cache = (duration: number | string) => {
55 const _lifetime = parseDuration(duration, 3600000)
56 return cacheRoute(_lifetime)
59 // ---------------------------------------------------------------------------