arnaucube
arnaucube/thoughtsPublic Self-hosted repository
thoughts/node_modules/mongoose/lib/virtualtype.js
node_modules/mongoose/lib/virtualtype.jsRaw
  1
  2/**
  3 * VirtualType constructor
  4 *
  5 * This is what mongoose uses to define virtual attributes via `Schema.prototype.virtual`.
  6 *
  7 * ####Example:
  8 *
  9 *     var fullname = schema.virtual('fullname');
 10 *     fullname instanceof mongoose.VirtualType // true
 11 *
 12 * @parma {Object} options
 13 * @api public
 14 */
 15
 16function VirtualType(options, name) {
 17  this.path = name;
 18  this.getters = [];
 19  this.setters = [];
 20  this.options = options || {};
 21}
 22
 23/**
 24 * Defines a getter.
 25 *
 26 * ####Example:
 27 *
 28 *     var virtual = schema.virtual('fullname');
 29 *     virtual.get(function () {
 30 *       return this.name.first + ' ' + this.name.last;
 31 *     });
 32 *
 33 * @param {Function} fn
 34 * @return {VirtualType} this
 35 * @api public
 36 */
 37
 38VirtualType.prototype.get = function(fn) {
 39  this.getters.push(fn);
 40  return this;
 41};
 42
 43/**
 44 * Defines a setter.
 45 *
 46 * ####Example:
 47 *
 48 *     var virtual = schema.virtual('fullname');
 49 *     virtual.set(function (v) {
 50 *       var parts = v.split(' ');
 51 *       this.name.first = parts[0];
 52 *       this.name.last = parts[1];
 53 *     });
 54 *
 55 * @param {Function} fn
 56 * @return {VirtualType} this
 57 * @api public
 58 */
 59
 60VirtualType.prototype.set = function(fn) {
 61  this.setters.push(fn);
 62  return this;
 63};
 64
 65/**
 66 * Applies getters to `value` using optional `scope`.
 67 *
 68 * @param {Object} value
 69 * @param {Object} scope
 70 * @return {any} the value after applying all getters
 71 * @api public
 72 */
 73
 74VirtualType.prototype.applyGetters = function(value, scope) {
 75  var v = value;
 76  for (var l = this.getters.length - 1; l >= 0; l--) {
 77    v = this.getters[l].call(scope, v, this);
 78  }
 79  return v;
 80};
 81
 82/**
 83 * Applies setters to `value` using optional `scope`.
 84 *
 85 * @param {Object} value
 86 * @param {Object} scope
 87 * @return {any} the value after applying all setters
 88 * @api public
 89 */
 90
 91VirtualType.prototype.applySetters = function(value, scope) {
 92  var v = value;
 93  for (var l = this.setters.length - 1; l >= 0; l--) {
 94    v = this.setters[l].call(scope, v, this);
 95  }
 96  return v;
 97};
 98
 99/*!
100 * exports
101 */
102
103module.exports = VirtualType;