Fix nodeinfo endpoint
[oweals/peertube.git] / server / middlewares / cache.ts
1 import * as express from 'express'
2 import * as AsyncLock from 'async-lock'
3 import { parseDuration } from '../helpers/utils'
4 import { Redis } from '../lib/redis'
5 import { logger } from '../helpers/logger'
6
7 const lock = new AsyncLock({ timeout: 5000 })
8
9 function cacheRoute (lifetimeArg: string | number) {
10   return async function (req: express.Request, res: express.Response, next: express.NextFunction) {
11     const redisKey = Redis.Instance.buildCachedRouteKey(req)
12
13     try {
14       await lock.acquire(redisKey, async (done) => {
15         const cached = await Redis.Instance.getCachedRoute(req)
16
17         // Not cached
18         if (!cached) {
19           logger.debug('No cached results for route %s.', req.originalUrl)
20
21           const sendSave = res.send.bind(res)
22
23           res.send = (body) => {
24             if (res.statusCode >= 200 && res.statusCode < 400) {
25               const contentType = res.get('content-type')
26               const lifetime = parseDuration(lifetimeArg)
27
28               Redis.Instance.setCachedRoute(req, body, lifetime, contentType, res.statusCode)
29                    .then(() => done())
30                    .catch(err => {
31                      logger.error('Cannot cache route.', { err })
32                      return done(err)
33                    })
34             }
35
36             return sendSave(body)
37           }
38
39           return next()
40         }
41
42         if (cached.contentType) res.set('content-type', cached.contentType)
43
44         if (cached.statusCode) {
45           const statusCode = parseInt(cached.statusCode, 10)
46           if (!isNaN(statusCode)) res.status(statusCode)
47         }
48
49         logger.debug('Use cached result for %s.', req.originalUrl)
50         res.send(cached.body).end()
51
52         return done()
53       })
54     } catch (err) {
55       logger.error('Cannot serve cached route.', err)
56       return next()
57     }
58   }
59 }
60
61 // ---------------------------------------------------------------------------
62
63 export {
64   cacheRoute
65 }