summaryrefslogtreecommitdiff
path: root/node_modules/mongoose/lib/virtualtype.js
blob: 5779df77d84e980dbca7ef8747616391a937eb96 (plain)
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
/**
 * VirtualType constructor
 *
 * This is what mongoose uses to define virtual attributes via
 * `Schema.prototype.virtual`
 *
 * @api public
 */

function VirtualType (options) {
  this.getters = [];
  this.setters = [];
  this.options = options || {};
}

/**
 * Adds a getter
 * 
 * @param {Function} fn
 * @return {VirtualType} this
 * @api public
 */

VirtualType.prototype.get = function (fn) {
  this.getters.push(fn);
  return this;
};

/**
 * Adds a setter
 * 
 * @param {Function} fn
 * @return {VirtualType} this
 * @api public
 */

VirtualType.prototype.set = function (fn) {
  this.setters.push(fn);
  return this;
};

/**
 * Applies getters
 *
 * @param {Object} value
 * @param {Object} scope
 * @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);
  }
  return v;
};

/**
 * Applies setters
 *
 * @param {Object} value
 * @param {Object} scope
 * @api public
 */

VirtualType.prototype.applySetters = function (value, scope) {
  var v = value;
  for (var l = this.setters.length - 1; l >= 0; l--){
    this.setters[l].call(scope, v);
  }
  return v;
};

module.exports = VirtualType;