]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/middlewares/cache.ts
Fix insane SQL request when loading all video attributes
[github/Chocobozzz/PeerTube.git] / server / middlewares / cache.ts
CommitLineData
4195cd2b
C
1import * as express from 'express'
2import { Redis } from '../lib/redis'
3import { logger } from '../helpers/logger'
4
fd4484f1
C
5function cacheRoute (lifetime: number) {
6 return async function (req: express.Request, res: express.Response, next: express.NextFunction) {
7 const cached = await Redis.Instance.getCachedRoute(req)
4195cd2b 8
fd4484f1
C
9 // Not cached
10 if (!cached) {
11 logger.debug('Not cached result for route %s.', req.originalUrl)
4195cd2b 12
fd4484f1 13 const sendSave = res.send.bind(res)
4195cd2b 14
fd4484f1
C
15 res.send = (body) => {
16 if (res.statusCode >= 200 && res.statusCode < 400) {
17 const contentType = res.getHeader('content-type').toString()
18 Redis.Instance.setCachedRoute(req, body, lifetime, contentType, res.statusCode)
19 .catch(err => logger.error('Cannot cache route.', { err }))
20 }
21
22 return sendSave(body)
4195cd2b
C
23 }
24
fd4484f1 25 return next()
4195cd2b
C
26 }
27
fd4484f1 28 if (cached.contentType) res.contentType(cached.contentType)
4195cd2b 29
fd4484f1
C
30 if (cached.statusCode) {
31 const statusCode = parseInt(cached.statusCode, 10)
32 if (!isNaN(statusCode)) res.status(statusCode)
33 }
4195cd2b 34
fd4484f1
C
35 logger.debug('Use cached result for %s.', req.originalUrl)
36 return res.send(cached.body).end()
4195cd2b 37 }
4195cd2b
C
38}
39
40// ---------------------------------------------------------------------------
41
42export {
43 cacheRoute
44}