-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
64 lines (51 loc) · 1.47 KB
/
index.js
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
var each = require('each')
, type = require('type')
, bind = require('bind');
/**
* Plugin.
*
* @param {Function|Object} models The models to warm the cache with or the
* Model constructor for the plugin.
*/
module.exports = function (models) {
// just the plugin
if ('function' === type(models)) return new Memoizer(models);
// warming cache with models
return function (Model) {
new Memoizer(Model, models);
};
};
/**
* Initialize a new `Memoizer`.
*
* @param {Model} Model The Model constructor to memoize.
* @param {Array} models Optional array of models to warm the cache with.
*/
function Memoizer (Model, models) {
this.Model = Model;
this._get = bind(Model, Model.get);
Model.get = bind(this, this.get);
Model.on('construct', function (model) {
cache[model.primary()] = model;
});
var cache = this.cache = {};
if (models) each(models, function (attrs) {
var model = new Model(attrs);
cache[model.primary()] = model;
});
}
/**
* Check the cache before getting a model from the server.
*
* @param {String} id The primary key for the model.
* @param {Function} callback Called with `err, model`.
*/
Memoizer.prototype.get = function (id, callback) {
var cache = this.cache;
if (cache[id]) return callback(null, cache[id]);
this._get(id, function (err, model) {
if (err || !model) return callback(err);
cache[model.primary()] = model;
callback(null, model);
});
};