handleImmutable.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. 'use strict';
  2. const StrictModeError = require('../../error/strict');
  3. /**
  4. * Handle immutable option for a given path when casting updates based on options
  5. *
  6. * @param {SchemaType} schematype the resolved schematype for this path
  7. * @param {Boolean | 'throw' | null} strict whether strict mode is set for this query
  8. * @param {Object} obj the object containing the value being checked so we can delete
  9. * @param {String} key the key in `obj` which we are checking for immutability
  10. * @param {String} fullPath the full path being checked
  11. * @param {Object} options the query options
  12. * @param {Query} ctx the query. Passed as `this` and first param to the `immutable` option, if `immutable` is a function
  13. * @returns true if field was removed, false otherwise
  14. */
  15. module.exports = function handleImmutable(schematype, strict, obj, key, fullPath, options, ctx) {
  16. if (!schematype?.options?.immutable) {
  17. return false;
  18. }
  19. let immutable = schematype.options.immutable;
  20. if (typeof immutable === 'function') {
  21. immutable = immutable.call(ctx, ctx);
  22. }
  23. if (!immutable) {
  24. return false;
  25. }
  26. if (options?.overwriteImmutable) {
  27. return false;
  28. }
  29. if (strict === false) {
  30. return false;
  31. }
  32. if (strict === 'throw') {
  33. throw new StrictModeError(null,
  34. `Field ${fullPath} is immutable and strict = 'throw'`);
  35. }
  36. delete obj[key];
  37. return true;
  38. };