]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/middlewares/cache.ts
adding initial support for nodeinfo
[github/Chocobozzz/PeerTube.git] / server / middlewares / cache.ts
CommitLineData
4195cd2b 1import * as express from 'express'
b40f0575 2import * as AsyncLock from 'async-lock'
3f6d68d9 3import { parseDuration } from '../helpers/utils'
4195cd2b
C
4import { Redis } from '../lib/redis'
5import { logger } from '../helpers/logger'
6
b40f0575
C
7const lock = new AsyncLock({ timeout: 5000 })
8
fd4484f1
C
9function cacheRoute (lifetime: number) {
10 return async function (req: express.Request, res: express.Response, next: express.NextFunction) {
b40f0575
C
11 const redisKey = Redis.Instance.buildCachedRouteKey(req)
12
13 await lock.acquire(redisKey, async (done) => {
14 const cached = await Redis.Instance.getCachedRoute(req)
4195cd2b 15
b40f0575
C
16 // Not cached
17 if (!cached) {
2186386c 18 logger.debug('No cached results for route %s.', req.originalUrl)
4195cd2b 19
b40f0575 20 const sendSave = res.send.bind(res)
4195cd2b 21
b40f0575
C
22 res.send = (body) => {
23 if (res.statusCode >= 200 && res.statusCode < 400) {
3f6d68d9 24 const contentType = res.get('content-type')
b40f0575
C
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)
fd4484f1
C
34 }
35
b40f0575 36 return next()
4195cd2b
C
37 }
38
3f6d68d9 39 if (cached.contentType) res.set('content-type', cached.contentType)
4195cd2b 40
b40f0575
C
41 if (cached.statusCode) {
42 const statusCode = parseInt(cached.statusCode, 10)
43 if (!isNaN(statusCode)) res.status(statusCode)
44 }
4195cd2b 45
b40f0575
C
46 logger.debug('Use cached result for %s.', req.originalUrl)
47 res.send(cached.body).end()
4195cd2b 48
b40f0575
C
49 return done()
50 })
4195cd2b 51 }
4195cd2b
C
52}
53
3f6d68d9
RK
54const cache = (duration: number | string) => {
55 const _lifetime = parseDuration(duration, 3600000)
56 return cacheRoute(_lifetime)
57}
58
4195cd2b
C
59// ---------------------------------------------------------------------------
60
61export {
3f6d68d9
RK
62 cacheRoute,
63 cache
4195cd2b 64}