All files / mongoose/lib/helpers/schematype handleImmutable.js

26.08% Statements 6/23
4.16% Branches 1/24
50% Functions 2/4
26.08% Lines 6/23

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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    1x           1x 2x 2x   2x                 2x                                                          
'use strict';
 
const StrictModeError = require('../../error/strict');
 
/*!
 * ignore
 */
 
module.exports = function(schematype) {
  Eif (schematype.$immutable) {
    schematype.$immutableSetter = createImmutableSetter(schematype.path,
      schematype.options.immutable);
    schematype.set(schematype.$immutableSetter);
  } else if (schematype.$immutableSetter) {
    schematype.setters = schematype.setters.
      filter(fn => fn !== schematype.$immutableSetter);
    delete schematype.$immutableSetter;
  }
};
 
function createImmutableSetter(path, immutable) {
  return function immutableSetter(v, _priorVal, _doc, options) {
    if (this == null || this.$__ == null) {
      return v;
    }
    if (this.isNew) {
      return v;
    }
    if (options && options.overwriteImmutable) {
      return v;
    }
 
    const _immutable = typeof immutable === 'function' ?
      immutable.call(this, this) :
      immutable;
    if (!_immutable) {
      return v;
    }
 
    const _value = this.$__.priorDoc != null ?
      this.$__.priorDoc.$__getValue(path) :
      this.$__getValue(path);
    if (this.$__.strictMode === 'throw' && v !== _value) {
      throw new StrictModeError(path, 'Path `' + path + '` is immutable ' +
        'and strict mode is set to throw.', true);
    }
 
    return _value;
  };
}