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