1
0
Fork 0
peertube/server/middlewares/cache.ts

45 lines
1.3 KiB
TypeScript
Raw Normal View History

2018-04-17 12:01:06 +00:00
import * as express from 'express'
import { Redis } from '../lib/redis'
import { logger } from '../helpers/logger'
2018-05-11 07:44:04 +00:00
function cacheRoute (lifetime: number) {
return async function (req: express.Request, res: express.Response, next: express.NextFunction) {
const cached = await Redis.Instance.getCachedRoute(req)
2018-04-17 12:01:06 +00:00
2018-05-11 07:44:04 +00:00
// Not cached
if (!cached) {
logger.debug('Not cached result for route %s.', req.originalUrl)
2018-04-17 12:01:06 +00:00
2018-05-11 07:44:04 +00:00
const sendSave = res.send.bind(res)
2018-04-17 12:01:06 +00:00
2018-05-11 07:44:04 +00:00
res.send = (body) => {
if (res.statusCode >= 200 && res.statusCode < 400) {
const contentType = res.getHeader('content-type').toString()
Redis.Instance.setCachedRoute(req, body, lifetime, contentType, res.statusCode)
.catch(err => logger.error('Cannot cache route.', { err }))
}
return sendSave(body)
2018-04-17 12:01:06 +00:00
}
2018-05-11 07:44:04 +00:00
return next()
2018-04-17 12:01:06 +00:00
}
2018-05-11 07:44:04 +00:00
if (cached.contentType) res.contentType(cached.contentType)
2018-04-17 12:01:06 +00:00
2018-05-11 07:44:04 +00:00
if (cached.statusCode) {
const statusCode = parseInt(cached.statusCode, 10)
if (!isNaN(statusCode)) res.status(statusCode)
}
2018-04-17 12:01:06 +00:00
2018-05-11 07:44:04 +00:00
logger.debug('Use cached result for %s.', req.originalUrl)
return res.send(cached.body).end()
2018-04-17 12:01:06 +00:00
}
}
// ---------------------------------------------------------------------------
export {
cacheRoute
}