cache.ts 2.11 KB
Newer Older
Chocobozzz's avatar
Chocobozzz committed
1
import * as express from 'express'
2
import * as AsyncLock from 'async-lock'
3
import { parseDurationToMs } from '../helpers/core-utils'
Chocobozzz's avatar
Chocobozzz committed
4
5
6
import { Redis } from '../lib/redis'
import { logger } from '../helpers/logger'

7
8
const lock = new AsyncLock({ timeout: 5000 })

Chocobozzz's avatar
Chocobozzz committed
9
function cacheRoute (lifetimeArg: string | number) {
Chocobozzz's avatar
Chocobozzz committed
10
11
  const lifetime = parseDurationToMs(lifetimeArg)

12
  return async function (req: express.Request, res: express.Response, next: express.NextFunction) {
13
    const redisKey = Redis.Instance.generateCachedRouteKey(req)
14

Chocobozzz's avatar
Chocobozzz committed
15
16
17
    try {
      await lock.acquire(redisKey, async (done) => {
        const cached = await Redis.Instance.getCachedRoute(req)
Chocobozzz's avatar
Chocobozzz committed
18

Chocobozzz's avatar
Chocobozzz committed
19
20
21
        // Not cached
        if (!cached) {
          logger.debug('No cached results for route %s.', req.originalUrl)
Chocobozzz's avatar
Chocobozzz committed
22

Chocobozzz's avatar
Chocobozzz committed
23
          const sendSave = res.send.bind(res)
Chocobozzz's avatar
Chocobozzz committed
24
          const redirectSave = res.redirect.bind(res)
Chocobozzz's avatar
Chocobozzz committed
25

Chocobozzz's avatar
Chocobozzz committed
26
27
28
29
30
31
32
33
34
35
          res.send = (body) => {
            if (res.statusCode >= 200 && res.statusCode < 400) {
              const contentType = res.get('content-type')

              Redis.Instance.setCachedRoute(req, body, lifetime, contentType, res.statusCode)
                   .then(() => done())
                   .catch(err => {
                     logger.error('Cannot cache route.', { err })
                     return done(err)
                   })
36
37
            } else {
              done()
Chocobozzz's avatar
Chocobozzz committed
38
39
40
            }

            return sendSave(body)
41
42
          }

Chocobozzz's avatar
Chocobozzz committed
43
44
45
46
47
48
          res.redirect = url => {
            done()

            return redirectSave(url)
          }

Chocobozzz's avatar
Chocobozzz committed
49
          return next()
50
51
        }

Chocobozzz's avatar
Chocobozzz committed
52
        if (cached.contentType) res.set('content-type', cached.contentType)
Chocobozzz's avatar
Chocobozzz committed
53

Chocobozzz's avatar
Chocobozzz committed
54
55
56
57
        if (cached.statusCode) {
          const statusCode = parseInt(cached.statusCode, 10)
          if (!isNaN(statusCode)) res.status(statusCode)
        }
Chocobozzz's avatar
Chocobozzz committed
58

Chocobozzz's avatar
Chocobozzz committed
59
60
        logger.debug('Use cached result for %s.', req.originalUrl)
        res.send(cached.body).end()
Chocobozzz's avatar
Chocobozzz committed
61

Chocobozzz's avatar
Chocobozzz committed
62
63
64
        return done()
      })
    } catch (err) {
65
      logger.error('Cannot serve cached route.', { err })
Chocobozzz's avatar
Chocobozzz committed
66
67
      return next()
    }
Chocobozzz's avatar
Chocobozzz committed
68
69
70
71
72
73
  }
}

// ---------------------------------------------------------------------------

export {
Chocobozzz's avatar
Chocobozzz committed
74
  cacheRoute
Chocobozzz's avatar
Chocobozzz committed
75
}