embedded.js 6.17 KB
Newer Older
jatuporn Tonggasem's avatar
jatuporn Tonggasem committed
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 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
'use strict';

/*!
 * Module dependencies.
 */

var $exists = require('./operators/exists');
var EventEmitter = require('events').EventEmitter;
var SchemaType = require('../schematype');
var castToNumber = require('./operators/helpers').castToNumber;
var discriminator = require('../services/model/discriminator');
var geospatial = require('./operators/geospatial');

var Subdocument;

module.exports = Embedded;

/**
 * Sub-schema schematype constructor
 *
 * @param {Schema} schema
 * @param {String} key
 * @param {Object} options
 * @inherits SchemaType
 * @api public
 */

function Embedded(schema, path, options) {
  this.caster = _createConstructor(schema);
  this.caster.prototype.$basePath = path;
  this.schema = schema;
  this.$isSingleNested = true;
  SchemaType.call(this, path, options, 'Embedded');
}

/*!
 * ignore
 */

Embedded.prototype = Object.create(SchemaType.prototype);

/*!
 * ignore
 */

function _createConstructor(schema) {
  // lazy load
  Subdocument || (Subdocument = require('../types/subdocument'));

  var _embedded = function SingleNested(value, path, parent) {
    var _this = this;

    this.$parent = parent;
    Subdocument.apply(this, arguments);

    if (parent) {
      parent.on('save', function() {
        _this.emit('save', _this);
        _this.constructor.emit('save', _this);
      });

      parent.on('isNew', function(val) {
        _this.isNew = val;
        _this.emit('isNew', val);
        _this.constructor.emit('isNew', val);
      });
    }
  };
  _embedded.prototype = Object.create(Subdocument.prototype);
  _embedded.prototype.$__setSchema(schema);
  _embedded.prototype.constructor = _embedded;
  _embedded.schema = schema;
  _embedded.$isSingleNested = true;
  _embedded.prototype.toBSON = function() {
    return this.toObject({
      transform: false,
      retainKeyOrder: true,
      virtuals: false,
      _skipDepopulateTopLevel: true,
      depopulate: true,
      flattenDecimals: false
    });
  };

  // apply methods
  for (var i in schema.methods) {
    _embedded.prototype[i] = schema.methods[i];
  }

  // apply statics
  for (i in schema.statics) {
    _embedded[i] = schema.statics[i];
  }

  for (i in EventEmitter.prototype) {
    _embedded[i] = EventEmitter.prototype[i];
  }

  return _embedded;
}

/*!
 * Special case for when users use a common location schema to represent
 * locations for use with $geoWithin.
 * https://docs.mongodb.org/manual/reference/operator/query/geoWithin/
 *
 * @param {Object} val
 * @api private
 */

Embedded.prototype.$conditionalHandlers.$geoWithin = function handle$geoWithin(val) {
  return { $geometry: this.castForQuery(val.$geometry) };
};

/*!
 * ignore
 */

Embedded.prototype.$conditionalHandlers.$near =
Embedded.prototype.$conditionalHandlers.$nearSphere = geospatial.cast$near;

Embedded.prototype.$conditionalHandlers.$within =
Embedded.prototype.$conditionalHandlers.$geoWithin = geospatial.cast$within;

Embedded.prototype.$conditionalHandlers.$geoIntersects =
  geospatial.cast$geoIntersects;

Embedded.prototype.$conditionalHandlers.$minDistance = castToNumber;
Embedded.prototype.$conditionalHandlers.$maxDistance = castToNumber;

Embedded.prototype.$conditionalHandlers.$exists = $exists;

/**
 * Casts contents
 *
 * @param {Object} value
 * @api private
 */

Embedded.prototype.cast = function(val, doc, init, priorVal) {
  if (val && val.$isSingleNested) {
    return val;
  }

  var Constructor = this.caster;
  var discriminatorKey = Constructor.schema.options.discriminatorKey;
  if (val != null &&
      Constructor.discriminators &&
      typeof val[discriminatorKey] === 'string' &&
      Constructor.discriminators[val[discriminatorKey]]) {
    Constructor = Constructor.discriminators[val[discriminatorKey]];
  }

  var subdoc;
  if (init) {
    subdoc = new Constructor(void 0, doc ? doc.$__.selected : void 0, doc);
    subdoc.init(val);
  } else {
    if (Object.keys(val).length === 0) {
      return new Constructor({}, doc ? doc.$__.selected : void 0, doc);
    }

    return new Constructor(val, doc ? doc.$__.selected : void 0, doc, undefined, {
      priorDoc: priorVal
    });
  }

  return subdoc;
};

/**
 * Casts contents for query
 *
 * @param {string} [$conditional] optional query operator (like `$eq` or `$in`)
 * @param {any} value
 * @api private
 */

Embedded.prototype.castForQuery = function($conditional, val) {
  var handler;
  if (arguments.length === 2) {
    handler = this.$conditionalHandlers[$conditional];
    if (!handler) {
      throw new Error('Can\'t use ' + $conditional);
    }
    return handler.call(this, val);
  }
  val = $conditional;
  if (val == null) {
    return val;
  }

  if (this.options.runSetters) {
    val = this._applySetters(val);
  }

  return new this.caster(val);
};

/**
 * Async validation on this single nested doc.
 *
 * @api private
 */

Embedded.prototype.doValidate = function(value, fn, scope) {
  var Constructor = this.caster;
  var discriminatorKey = Constructor.schema.options.discriminatorKey;
  if (value != null &&
      Constructor.discriminators &&
      typeof value[discriminatorKey] === 'string' &&
      Constructor.discriminators[value[discriminatorKey]]) {
    Constructor = Constructor.discriminators[value[discriminatorKey]];
  }

  SchemaType.prototype.doValidate.call(this, value, function(error) {
    if (error) {
      return fn(error);
    }
    if (!value) {
      return fn(null);
    }

    if (!(value instanceof Constructor)) {
      value = new Constructor(value);
    }
    value.validate({__noPromise: true}, fn);
  }, scope);
};

/**
 * Synchronously validate this single nested doc
 *
 * @api private
 */

Embedded.prototype.doValidateSync = function(value, scope) {
  var schemaTypeError = SchemaType.prototype.doValidateSync.call(this, value, scope);
  if (schemaTypeError) {
    return schemaTypeError;
  }
  if (!value) {
    return;
  }
  return value.validateSync();
};

/**
 * Adds a discriminator to this property
 *
 * @param {String} name
 * @param {Schema} schema fields to add to the schema for instances of this sub-class
 * @api public
 */

Embedded.prototype.discriminator = function(name, schema) {
  discriminator(this.caster, name, schema);

  this.caster.discriminators[name] = _createConstructor(schema);

  return this.caster.discriminators[name];
};