2018-04-17 14:01:06 +02:00
|
|
|
import * as express from 'express'
|
2018-05-23 10:03:26 +02:00
|
|
|
import * as AsyncLock from 'async-lock'
|
2018-07-21 23:00:25 +02:00
|
|
|
import { parseDuration } from '../helpers/utils'
|
2018-04-17 14:01:06 +02:00
|
|
|
import { Redis } from '../lib/redis'
|
|
|
|
import { logger } from '../helpers/logger'
|
|
|
|
|
2018-05-23 10:03:26 +02:00
|
|
|
const lock = new AsyncLock({ timeout: 5000 })
|
|
|
|
|
2018-05-11 09:44:04 +02:00
|
|
|
function cacheRoute (lifetime: number) {
|
|
|
|
return async function (req: express.Request, res: express.Response, next: express.NextFunction) {
|
2018-05-23 10:03:26 +02:00
|
|
|
const redisKey = Redis.Instance.buildCachedRouteKey(req)
|
|
|
|
|
|
|
|
await lock.acquire(redisKey, async (done) => {
|
|
|
|
const cached = await Redis.Instance.getCachedRoute(req)
|
2018-04-17 14:01:06 +02:00
|
|
|
|
2018-05-23 10:03:26 +02:00
|
|
|
// Not cached
|
|
|
|
if (!cached) {
|
2018-06-12 20:04:58 +02:00
|
|
|
logger.debug('No cached results for route %s.', req.originalUrl)
|
2018-04-17 14:01:06 +02:00
|
|
|
|
2018-05-23 10:03:26 +02:00
|
|
|
const sendSave = res.send.bind(res)
|
2018-04-17 14:01:06 +02:00
|
|
|
|
2018-05-23 10:03:26 +02:00
|
|
|
res.send = (body) => {
|
|
|
|
if (res.statusCode >= 200 && res.statusCode < 400) {
|
2018-07-21 23:00:25 +02:00
|
|
|
const contentType = res.get('content-type')
|
2018-05-23 10:03:26 +02:00
|
|
|
Redis.Instance.setCachedRoute(req, body, lifetime, contentType, res.statusCode)
|
|
|
|
.then(() => done())
|
|
|
|
.catch(err => {
|
|
|
|
logger.error('Cannot cache route.', { err })
|
|
|
|
return done(err)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
return sendSave(body)
|
2018-05-11 09:44:04 +02:00
|
|
|
}
|
|
|
|
|
2018-05-23 10:03:26 +02:00
|
|
|
return next()
|
2018-04-17 14:01:06 +02:00
|
|
|
}
|
|
|
|
|
2018-07-21 23:00:25 +02:00
|
|
|
if (cached.contentType) res.set('content-type', cached.contentType)
|
2018-04-17 14:01:06 +02:00
|
|
|
|
2018-05-23 10:03:26 +02:00
|
|
|
if (cached.statusCode) {
|
|
|
|
const statusCode = parseInt(cached.statusCode, 10)
|
|
|
|
if (!isNaN(statusCode)) res.status(statusCode)
|
|
|
|
}
|
2018-04-17 14:01:06 +02:00
|
|
|
|
2018-05-23 10:03:26 +02:00
|
|
|
logger.debug('Use cached result for %s.', req.originalUrl)
|
|
|
|
res.send(cached.body).end()
|
2018-04-17 14:01:06 +02:00
|
|
|
|
2018-05-23 10:03:26 +02:00
|
|
|
return done()
|
|
|
|
})
|
2018-04-17 14:01:06 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-07-21 23:00:25 +02:00
|
|
|
const cache = (duration: number | string) => {
|
|
|
|
const _lifetime = parseDuration(duration, 3600000)
|
|
|
|
return cacheRoute(_lifetime)
|
|
|
|
}
|
|
|
|
|
2018-04-17 14:01:06 +02:00
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
|
|
export {
|
2018-07-21 23:00:25 +02:00
|
|
|
cacheRoute,
|
|
|
|
cache
|
2018-04-17 14:01:06 +02:00
|
|
|
}
|