]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/middlewares/cache.ts
1e5a13b2e0394952409d71e6db8acb23cdf3a5ac
[github/Chocobozzz/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 (lifetime: number) {
10 return async function (req: express.Request, res: express.Response, next: express.NextFunction) {
11 const redisKey = Redis.Instance.buildCachedRouteKey(req)
12
13 await lock.acquire(redisKey, async (done) => {
14 const cached = await Redis.Instance.getCachedRoute(req)
15
16 // Not cached
17 if (!cached) {
18 logger.debug('No cached results for route %s.', req.originalUrl)
19
20 const sendSave = res.send.bind(res)
21
22 res.send = (body) => {
23 if (res.statusCode >= 200 && res.statusCode < 400) {
24 const contentType = res.get('content-type')
25 Redis.Instance.setCachedRoute(req, body, lifetime, contentType, res.statusCode)
26 .then(() => done())
27 .catch(err => {
28 logger.error('Cannot cache route.', { err })
29 return done(err)
30 })
31 }
32
33 return sendSave(body)
34 }
35
36 return next()
37 }
38
39 if (cached.contentType) res.set('content-type', cached.contentType)
40
41 if (cached.statusCode) {
42 const statusCode = parseInt(cached.statusCode, 10)
43 if (!isNaN(statusCode)) res.status(statusCode)
44 }
45
46 logger.debug('Use cached result for %s.', req.originalUrl)
47 res.send(cached.body).end()
48
49 return done()
50 })
51 }
52 }
53
54 const cache = (duration: number | string) => {
55 const _lifetime = parseDuration(duration, 3600000)
56 return cacheRoute(_lifetime)
57 }
58
59 // ---------------------------------------------------------------------------
60
61 export {
62 cacheRoute,
63 cache
64 }