aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/middlewares/cache.ts
diff options
context:
space:
mode:
authorChocobozzz <me@florianbigard.com>2018-04-17 14:01:06 +0200
committerChocobozzz <me@florianbigard.com>2018-04-17 14:04:34 +0200
commit4195cd2bc5046d4cdf1c677c27cd41f427d7a13a (patch)
tree3300258d96a427da29cc4785686d741e336102bb /server/middlewares/cache.ts
parentcff8b272b1631661b8d5f5f4b59bd534ad8c86ca (diff)
downloadPeerTube-4195cd2bc5046d4cdf1c677c27cd41f427d7a13a.tar.gz
PeerTube-4195cd2bc5046d4cdf1c677c27cd41f427d7a13a.tar.zst
PeerTube-4195cd2bc5046d4cdf1c677c27cd41f427d7a13a.zip
Add redis cache to feed route
Diffstat (limited to 'server/middlewares/cache.ts')
-rw-r--r--server/middlewares/cache.ts41
1 files changed, 41 insertions, 0 deletions
diff --git a/server/middlewares/cache.ts b/server/middlewares/cache.ts
new file mode 100644
index 000000000..a2c7f7cbd
--- /dev/null
+++ b/server/middlewares/cache.ts
@@ -0,0 +1,41 @@
1import * as express from 'express'
2import { Redis } from '../lib/redis'
3import { logger } from '../helpers/logger'
4
5async 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
39export {
40 cacheRoute
41}