forked from dresende/node-orm2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLazyLoad.js
More file actions
74 lines (61 loc) · 1.6 KB
/
LazyLoad.js
File metadata and controls
74 lines (61 loc) · 1.6 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
71
72
73
74
exports.extend = function (Instance, Model, properties) {
for (var k in properties) {
if (properties[k].lazyload === true) {
addLazyLoadProperty(properties[k].lazyname || k, Instance, Model, k);
}
}
};
function addLazyLoadProperty(name, Instance, Model, property) {
var method = ucfirst(name);
Object.defineProperty(Instance, "get" + method, {
value: function (cb) {
var conditions = {};
conditions[Model.id] = Instance[Model.id];
Model.find(conditions, { cache: false }).only(property).first(function (err, item) {
return cb(err, item ? item[property] : null);
});
return this;
},
enumerable: false
});
Object.defineProperty(Instance, "remove" + method, {
value: function (cb) {
var conditions = {};
conditions[Model.id] = Instance[Model.id];
Model.find(conditions, { cache: false }).only(property).first(function (err, item) {
if (err) {
return cb(err);
}
if (!item) {
return cb(null);
}
item[property] = null;
item[Model.id] = Instance[Model.id];
return item.save(cb);
});
return this;
},
enumerable: false
});
Object.defineProperty(Instance, "set" + method, {
value: function (data, cb) {
var conditions = {};
conditions[Model.id] = Instance[Model.id];
Model.find(conditions, { cache: false }).first(function (err, item) {
if (err) {
return cb(err);
}
if (!item) {
return cb(null);
}
item[property] = data;
return item.save(cb);
});
return this;
},
enumerable: false
});
}
function ucfirst(text) {
return text[0].toUpperCase() + text.substr(1).toLowerCase();
}