File size: 1,687 Bytes
c02f046
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
var cachou = require('cachou');
var cacheKey = require('./cache-key');

/**
 * Expose module.
 */

module.exports = resourceCacheFactory;

/**
 * Return a new instance of ResourceCache.
 *
 * @param {Object} options
 */

function resourceCacheFactory(options) {
  return new ResourceCache(options);
}

/**
 * Create a new instance of ResourceCache.
 *
 * @param {Object} options
 */

function ResourceCache(options) {
  var cache = this._cachou = cachou(options.cachou);
  var globalOptions = options;

  this.read = readFactory;
  this.populate = populateFactory;
  this.invalidate = invalidateFactory;

  /**
   * Read the cache and serve it if avalaible.
   */

  function readFactory(options) {
    options = options || globalOptions;

    return function read(req, res, next) {
      var key = cacheKey.format(options.name, req.query.id, req.query);

      cache.get(key, function (err, cacheRes) {
        if (err) return next(err);

        // Populate and body and stop.
        if (cacheRes) {
          res.body = cacheRes;
          res.end();
        }

        next();
      });
    };
  }

  /**
   * Populate the cache.
   */

  function populateFactory(options) {
    options = options || globalOptions;

    return function populate(req, res, next) {
      var key = cacheKey.format(options.name, req.query.id, req.query);
      cache.set(key, res.body);
      next();
    };
  }

  /**
   * Invalidate the cache.
   */

  function invalidateFactory(options) {
    options = options || globalOptions;

    return function invalidate(req, res, next) {
      var matcher = cacheKey.formatMatcher(options.name, req.query.id);
      cache.delAll(matcher, next);
    };
  }
}