aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/middlewares
diff options
context:
space:
mode:
Diffstat (limited to 'server/middlewares')
-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}