diff options
author | Chocobozzz <me@florianbigard.com> | 2018-04-17 14:01:06 +0200 |
---|---|---|
committer | Chocobozzz <me@florianbigard.com> | 2018-04-17 14:04:34 +0200 |
commit | 4195cd2bc5046d4cdf1c677c27cd41f427d7a13a (patch) | |
tree | 3300258d96a427da29cc4785686d741e336102bb /server/middlewares | |
parent | cff8b272b1631661b8d5f5f4b59bd534ad8c86ca (diff) | |
download | PeerTube-4195cd2bc5046d4cdf1c677c27cd41f427d7a13a.tar.gz PeerTube-4195cd2bc5046d4cdf1c677c27cd41f427d7a13a.tar.zst PeerTube-4195cd2bc5046d4cdf1c677c27cd41f427d7a13a.zip |
Add redis cache to feed route
Diffstat (limited to 'server/middlewares')
-rw-r--r-- | server/middlewares/cache.ts | 41 |
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 @@ | |||
1 | import * as express from 'express' | ||
2 | import { Redis } from '../lib/redis' | ||
3 | import { logger } from '../helpers/logger' | ||
4 | |||
5 | async 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 | |||
39 | export { | ||
40 | cacheRoute | ||
41 | } | ||