forked from Automattic/mongoose
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvirtualtype.js
103 lines (91 loc) · 1.99 KB
/
virtualtype.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/**
* VirtualType constructor
*
* This is what mongoose uses to define virtual attributes via `Schema.prototype.virtual`.
*
* ####Example:
*
* var fullname = schema.virtual('fullname');
* fullname instanceof mongoose.VirtualType // true
*
* @parma {Object} options
* @api public
*/
function VirtualType (options, name) {
this.path = name;
this.getters = [];
this.setters = [];
this.options = options || {};
}
/**
* Defines a getter.
*
* ####Example:
*
* var virtual = schema.virtual('fullname');
* virtual.get(function () {
* return this.name.first + ' ' + this.name.last;
* });
*
* @param {Function} fn
* @return {VirtualType} this
* @api public
*/
VirtualType.prototype.get = function (fn) {
this.getters.push(fn);
return this;
};
/**
* Defines a setter.
*
* ####Example:
*
* var virtual = schema.virtual('fullname');
* virtual.set(function (v) {
* var parts = v.split(' ');
* this.name.first = parts[0];
* this.name.last = parts[1];
* });
*
* @param {Function} fn
* @return {VirtualType} this
* @api public
*/
VirtualType.prototype.set = function (fn) {
this.setters.push(fn);
return this;
};
/**
* Applies getters to `value` using optional `scope`.
*
* @param {Object} value
* @param {Object} scope
* @return {any} the value after applying all getters
* @api public
*/
VirtualType.prototype.applyGetters = function (value, scope) {
var v = value;
for (var l = this.getters.length - 1; l >= 0; l--) {
v = this.getters[l].call(scope, v, this);
}
return v;
};
/**
* Applies setters to `value` using optional `scope`.
*
* @param {Object} value
* @param {Object} scope
* @return {any} the value after applying all setters
* @api public
*/
VirtualType.prototype.applySetters = function (value, scope) {
var v = value;
for (var l = this.setters.length - 1; l >= 0; l--) {
v = this.setters[l].call(scope, v, this);
}
return v;
};
/*!
* exports
*/
module.exports = VirtualType;