handleImmutable.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. 'use strict';
  2. const StrictModeError = require('../../error/strict');
  3. /*!
  4. * ignore
  5. */
  6. module.exports = function(schematype) {
  7. if (schematype.$immutable) {
  8. schematype.$immutableSetter = createImmutableSetter(schematype.path,
  9. schematype.options.immutable);
  10. schematype.set(schematype.$immutableSetter);
  11. } else if (schematype.$immutableSetter) {
  12. schematype.setters = schematype.setters.
  13. filter(fn => fn !== schematype.$immutableSetter);
  14. delete schematype.$immutableSetter;
  15. }
  16. };
  17. function createImmutableSetter(path, immutable) {
  18. return function immutableSetter(v, _priorVal, _doc, options) {
  19. if (this == null || this.$__ == null) {
  20. return v;
  21. }
  22. if (this.isNew) {
  23. return v;
  24. }
  25. if (options && options.overwriteImmutable) {
  26. return v;
  27. }
  28. const _immutable = typeof immutable === 'function' ?
  29. immutable.call(this, this) :
  30. immutable;
  31. if (!_immutable) {
  32. return v;
  33. }
  34. const _value = this.$__.priorDoc != null ?
  35. this.$__.priorDoc.$__getValue(path) :
  36. this.$__getValue(path);
  37. if (this.$__.strictMode === 'throw' && v !== _value) {
  38. throw new StrictModeError(path, 'Path `' + path + '` is immutable ' +
  39. 'and strict mode is set to throw.', true);
  40. }
  41. return _value;
  42. };
  43. }