cache.ts 1.81 KB
Newer Older
Chocobozzz's avatar
Chocobozzz committed
1
import * as express from 'express'
2
import * as AsyncLock from 'async-lock'
3
import { parseDuration } from '../helpers/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 })

9
10
function cacheRoute (lifetime: number) {
  return async function (req: express.Request, res: express.Response, next: express.NextFunction) {
11
12
13
14
    const redisKey = Redis.Instance.buildCachedRouteKey(req)

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

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

20
        const sendSave = res.send.bind(res)
Chocobozzz's avatar
Chocobozzz committed
21

22
23
        res.send = (body) => {
          if (res.statusCode >= 200 && res.statusCode < 400) {
24
            const contentType = res.get('content-type')
25
26
27
28
29
30
31
32
33
            Redis.Instance.setCachedRoute(req, body, lifetime, contentType, res.statusCode)
                 .then(() => done())
                 .catch(err => {
                   logger.error('Cannot cache route.', { err })
                   return done(err)
                 })
          }

          return sendSave(body)
34
35
        }

36
        return next()
Chocobozzz's avatar
Chocobozzz committed
37
38
      }

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

41
42
43
44
      if (cached.statusCode) {
        const statusCode = parseInt(cached.statusCode, 10)
        if (!isNaN(statusCode)) res.status(statusCode)
      }
Chocobozzz's avatar
Chocobozzz committed
45

46
47
      logger.debug('Use cached result for %s.', req.originalUrl)
      res.send(cached.body).end()
Chocobozzz's avatar
Chocobozzz committed
48

49
50
      return done()
    })
Chocobozzz's avatar
Chocobozzz committed
51
52
53
  }
}

54
55
56
57
58
const cache = (duration: number | string) => {
  const _lifetime = parseDuration(duration, 3600000)
  return cacheRoute(_lifetime)
}

Chocobozzz's avatar
Chocobozzz committed
59
60
61
// ---------------------------------------------------------------------------

export {
62
63
  cacheRoute,
  cache
Chocobozzz's avatar
Chocobozzz committed
64
}