cache.ts 1.27 KB
Newer Older
Chocobozzz's avatar
Chocobozzz committed
1
2
3
4
import * as express from 'express'
import { Redis } from '../lib/redis'
import { logger } from '../helpers/logger'

5
6
7
function cacheRoute (lifetime: number) {
  return async function (req: express.Request, res: express.Response, next: express.NextFunction) {
    const cached = await Redis.Instance.getCachedRoute(req)
Chocobozzz's avatar
Chocobozzz committed
8

9
10
11
    // Not cached
    if (!cached) {
      logger.debug('Not cached result for route %s.', req.originalUrl)
Chocobozzz's avatar
Chocobozzz committed
12

13
      const sendSave = res.send.bind(res)
Chocobozzz's avatar
Chocobozzz committed
14

15
16
17
18
19
20
21
22
      res.send = (body) => {
        if (res.statusCode >= 200 && res.statusCode < 400) {
          const contentType = res.getHeader('content-type').toString()
          Redis.Instance.setCachedRoute(req, body, lifetime, contentType, res.statusCode)
               .catch(err => logger.error('Cannot cache route.', { err }))
        }

        return sendSave(body)
Chocobozzz's avatar
Chocobozzz committed
23
24
      }

25
      return next()
Chocobozzz's avatar
Chocobozzz committed
26
27
    }

28
    if (cached.contentType) res.contentType(cached.contentType)
Chocobozzz's avatar
Chocobozzz committed
29

30
31
32
33
    if (cached.statusCode) {
      const statusCode = parseInt(cached.statusCode, 10)
      if (!isNaN(statusCode)) res.status(statusCode)
    }
Chocobozzz's avatar
Chocobozzz committed
34

35
36
    logger.debug('Use cached result for %s.', req.originalUrl)
    return res.send(cached.body).end()
Chocobozzz's avatar
Chocobozzz committed
37
38
39
40
41
42
43
44
  }
}

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

export {
  cacheRoute
}