]>
Commit | Line | Data |
---|---|---|
4195cd2b | 1 | import * as express from 'express' |
b40f0575 | 2 | import * as AsyncLock from 'async-lock' |
4195cd2b C |
3 | import { Redis } from '../lib/redis' |
4 | import { logger } from '../helpers/logger' | |
5 | ||
b40f0575 C |
6 | const lock = new AsyncLock({ timeout: 5000 }) |
7 | ||
fd4484f1 C |
8 | function cacheRoute (lifetime: number) { |
9 | return async function (req: express.Request, res: express.Response, next: express.NextFunction) { | |
b40f0575 C |
10 | const redisKey = Redis.Instance.buildCachedRouteKey(req) |
11 | ||
12 | await lock.acquire(redisKey, async (done) => { | |
13 | const cached = await Redis.Instance.getCachedRoute(req) | |
4195cd2b | 14 | |
b40f0575 C |
15 | // Not cached |
16 | if (!cached) { | |
2186386c | 17 | logger.debug('No cached results for route %s.', req.originalUrl) |
4195cd2b | 18 | |
b40f0575 | 19 | const sendSave = res.send.bind(res) |
4195cd2b | 20 | |
b40f0575 C |
21 | res.send = (body) => { |
22 | if (res.statusCode >= 200 && res.statusCode < 400) { | |
23 | const contentType = res.getHeader('content-type').toString() | |
24 | Redis.Instance.setCachedRoute(req, body, lifetime, contentType, res.statusCode) | |
25 | .then(() => done()) | |
26 | .catch(err => { | |
27 | logger.error('Cannot cache route.', { err }) | |
28 | return done(err) | |
29 | }) | |
30 | } | |
31 | ||
32 | return sendSave(body) | |
fd4484f1 C |
33 | } |
34 | ||
b40f0575 | 35 | return next() |
4195cd2b C |
36 | } |
37 | ||
b40f0575 | 38 | if (cached.contentType) res.contentType(cached.contentType) |
4195cd2b | 39 | |
b40f0575 C |
40 | if (cached.statusCode) { |
41 | const statusCode = parseInt(cached.statusCode, 10) | |
42 | if (!isNaN(statusCode)) res.status(statusCode) | |
43 | } | |
4195cd2b | 44 | |
b40f0575 C |
45 | logger.debug('Use cached result for %s.', req.originalUrl) |
46 | res.send(cached.body).end() | |
4195cd2b | 47 | |
b40f0575 C |
48 | return done() |
49 | }) | |
4195cd2b | 50 | } |
4195cd2b C |
51 | } |
52 | ||
53 | // --------------------------------------------------------------------------- | |
54 | ||
55 | export { | |
56 | cacheRoute | |
57 | } |