namedscope.js
1.66 KB
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
var Query = require('./query');
function NamedScope () {}
NamedScope.prototype.query;
NamedScope.prototype.where = function () {
var q = this.query || (this.query = new Query());
q.where.apply(q, arguments);
return q;
};
/**
* Decorate
*
* @param {NamedScope} target
* @param {Object} getters
* @api private
*/
NamedScope.prototype.decorate = function (target, getters) {
var name = this.name
, block = this.block
, query = this.query;
if (block) {
if (block.length === 0) {
Object.defineProperty(target, name, {
get: getters.block0(block)
});
} else {
target[name] = getters.blockN(block);
}
} else {
Object.defineProperty(target, name, {
get: getters.basic(query)
});
}
};
NamedScope.prototype.compile = function (model) {
var allScopes = this.scopesByName
, scope;
for (var k in allScopes) {
scope = allScopes[k];
scope.decorate(model, {
block0: function (block) {
return function () {
var cquery = this._cumulativeQuery || (this._cumulativeQuery = new Query().bind(this));
block.call(cquery);
return this;
};
},
blockN: function (block) {
return function () {
var cquery = this._cumulativeQuery || (this._cumulativeQuery = new Query().bind(this));
block.apply(cquery, arguments);
return this;
};
},
basic: function (query) {
return function () {
var cquery = this._cumulativeQuery || (this._cumulativeQuery = new Query().bind(this));
cquery.find(query);
return this;
};
}
});
}
};
module.exports = NamedScope;