c589ef683c1b1d64e4b04d4f28bb3bb7380f5993
[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 function cacheRoute (lifetime: number) {
6   return async function (req: express.Request, res: express.Response, next: express.NextFunction) {
7     const cached = await Redis.Instance.getCachedRoute(req)
8
9     // Not cached
10     if (!cached) {
11       logger.debug('Not cached result for route %s.', req.originalUrl)
12
13       const sendSave = res.send.bind(res)
14
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)
23       }
24
25       return next()
26     }
27
28     if (cached.contentType) res.contentType(cached.contentType)
29
30     if (cached.statusCode) {
31       const statusCode = parseInt(cached.statusCode, 10)
32       if (!isNaN(statusCode)) res.status(statusCode)
33     }
34
35     logger.debug('Use cached result for %s.', req.originalUrl)
36     return res.send(cached.body).end()
37   }
38 }
39
40 // ---------------------------------------------------------------------------
41
42 export {
43   cacheRoute
44 }