validateBeforeSave.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. 'use strict';
  2. /*!
  3. * ignore
  4. */
  5. module.exports = function validateBeforeSave(schema) {
  6. const unshift = true;
  7. schema.pre('save', false, async function validateBeforeSave(options) {
  8. // Nested docs have their own presave
  9. if (this.$isSubdocument) {
  10. return;
  11. }
  12. const hasValidateBeforeSaveOption = options &&
  13. (typeof options === 'object') &&
  14. ('validateBeforeSave' in options);
  15. let shouldValidate;
  16. if (hasValidateBeforeSaveOption) {
  17. shouldValidate = !!options.validateBeforeSave;
  18. } else {
  19. shouldValidate = this.$__schema.options.validateBeforeSave;
  20. }
  21. // Validate
  22. if (shouldValidate) {
  23. const hasValidateModifiedOnlyOption = options &&
  24. (typeof options === 'object') &&
  25. ('validateModifiedOnly' in options);
  26. const validateOptions = hasValidateModifiedOnlyOption ?
  27. { validateModifiedOnly: options.validateModifiedOnly } :
  28. null;
  29. await this.$validate(validateOptions).then(
  30. () => {
  31. this.$op = 'save';
  32. }
  33. );
  34. }
  35. }, null, unshift);
  36. };