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