modelValidate.js 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. const clone = require('./modelClone').clone;
  2. const { defineNonEnumerableProperty } = require('./modelUtils');
  3. function validate(model, json, options = {}) {
  4. json = json || model;
  5. const inputJson = json;
  6. const validatingModelInstance = inputJson && inputJson.$isObjectionModel;
  7. if (options.skipValidation) {
  8. return json;
  9. }
  10. if (validatingModelInstance) {
  11. // Strip away relations and other internal stuff.
  12. json = clone(json, true, true);
  13. // We can mutate `json` now that we took a copy of it.
  14. options = Object.assign({}, options, { mutable: true });
  15. }
  16. const ModelClass = model.constructor;
  17. const validator = ModelClass.getValidator();
  18. const args = {
  19. options,
  20. model,
  21. json,
  22. ctx: Object.create(null)
  23. };
  24. validator.beforeValidate(args);
  25. json = validator.validate(args);
  26. validator.afterValidate(args);
  27. if (validatingModelInstance) {
  28. // If we cloned `json`, we need to copy the possible default values.
  29. return inputJson.$set(json);
  30. } else {
  31. return json;
  32. }
  33. }
  34. module.exports = {
  35. validate
  36. };