instance-validator.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. "use strict";
  2. var __defProp = Object.defineProperty;
  3. var __getOwnPropSymbols = Object.getOwnPropertySymbols;
  4. var __hasOwnProp = Object.prototype.hasOwnProperty;
  5. var __propIsEnum = Object.prototype.propertyIsEnumerable;
  6. var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  7. var __spreadValues = (a, b) => {
  8. for (var prop in b || (b = {}))
  9. if (__hasOwnProp.call(b, prop))
  10. __defNormalProp(a, prop, b[prop]);
  11. if (__getOwnPropSymbols)
  12. for (var prop of __getOwnPropSymbols(b)) {
  13. if (__propIsEnum.call(b, prop))
  14. __defNormalProp(a, prop, b[prop]);
  15. }
  16. return a;
  17. };
  18. const _ = require("lodash");
  19. const Utils = require("./utils");
  20. const sequelizeError = require("./errors");
  21. const DataTypes = require("./data-types");
  22. const BelongsTo = require("./associations/belongs-to");
  23. const validator = require("./utils/validator-extras").validator;
  24. const { promisify } = require("util");
  25. class InstanceValidator {
  26. constructor(modelInstance, options) {
  27. options = __spreadValues({
  28. hooks: true
  29. }, options);
  30. if (options.fields && !options.skip) {
  31. options.skip = _.difference(Object.keys(modelInstance.constructor.rawAttributes), options.fields);
  32. } else {
  33. options.skip = options.skip || [];
  34. }
  35. this.options = options;
  36. this.modelInstance = modelInstance;
  37. this.validator = validator;
  38. this.errors = [];
  39. this.inProgress = false;
  40. }
  41. async _validate() {
  42. if (this.inProgress)
  43. throw new Error("Validations already in progress.");
  44. this.inProgress = true;
  45. await Promise.all([
  46. this._perAttributeValidators(),
  47. this._customValidators()
  48. ]);
  49. if (this.errors.length) {
  50. throw new sequelizeError.ValidationError(null, this.errors);
  51. }
  52. }
  53. async validate() {
  54. return await (this.options.hooks ? this._validateAndRunHooks() : this._validate());
  55. }
  56. async _validateAndRunHooks() {
  57. const runHooks = this.modelInstance.constructor.runHooks.bind(this.modelInstance.constructor);
  58. await runHooks("beforeValidate", this.modelInstance, this.options);
  59. try {
  60. await this._validate();
  61. } catch (error) {
  62. const newError = await runHooks("validationFailed", this.modelInstance, this.options, error);
  63. throw newError || error;
  64. }
  65. await runHooks("afterValidate", this.modelInstance, this.options);
  66. return this.modelInstance;
  67. }
  68. async _perAttributeValidators() {
  69. const validators = [];
  70. _.forIn(this.modelInstance.rawAttributes, (rawAttribute, field) => {
  71. if (this.options.skip.includes(field)) {
  72. return;
  73. }
  74. const value = this.modelInstance.dataValues[field];
  75. if (value instanceof Utils.SequelizeMethod) {
  76. return;
  77. }
  78. if (!rawAttribute._autoGenerated && !rawAttribute.autoIncrement) {
  79. this._validateSchema(rawAttribute, field, value);
  80. }
  81. if (Object.prototype.hasOwnProperty.call(this.modelInstance.validators, field)) {
  82. validators.push(this._singleAttrValidate(value, field, rawAttribute.allowNull));
  83. }
  84. });
  85. return await Promise.all(validators);
  86. }
  87. async _customValidators() {
  88. const validators = [];
  89. _.each(this.modelInstance.constructor.options.validate, (validator2, validatorType) => {
  90. if (this.options.skip.includes(validatorType)) {
  91. return;
  92. }
  93. const valprom = this._invokeCustomValidator(validator2, validatorType).catch(() => {
  94. });
  95. validators.push(valprom);
  96. });
  97. return await Promise.all(validators);
  98. }
  99. async _singleAttrValidate(value, field, allowNull) {
  100. if ((value === null || value === void 0) && !allowNull) {
  101. return;
  102. }
  103. const validators = [];
  104. _.forIn(this.modelInstance.validators[field], (test, validatorType) => {
  105. if (["isUrl", "isURL", "isEmail"].includes(validatorType)) {
  106. if (typeof test === "object" && test !== null && test.msg) {
  107. test = {
  108. msg: test.msg
  109. };
  110. } else if (test === true) {
  111. test = {};
  112. }
  113. }
  114. if (typeof test === "function") {
  115. validators.push(this._invokeCustomValidator(test, validatorType, true, value, field));
  116. return;
  117. }
  118. if (value === null || value === void 0) {
  119. return;
  120. }
  121. const validatorPromise = this._invokeBuiltinValidator(value, test, validatorType, field);
  122. validatorPromise.catch(() => {
  123. });
  124. validators.push(validatorPromise);
  125. });
  126. return Promise.all(validators.map((validator2) => validator2.catch((rejection) => {
  127. const isBuiltIn = !!rejection.validatorName;
  128. this._pushError(isBuiltIn, field, rejection, value, rejection.validatorName, rejection.validatorArgs);
  129. })));
  130. }
  131. async _invokeCustomValidator(validator2, validatorType, optAttrDefined, optValue, optField) {
  132. let isAsync = false;
  133. const validatorArity = validator2.length;
  134. let asyncArity = 1;
  135. let errorKey = validatorType;
  136. let invokeArgs;
  137. if (optAttrDefined) {
  138. asyncArity = 2;
  139. invokeArgs = optValue;
  140. errorKey = optField;
  141. }
  142. if (validatorArity === asyncArity) {
  143. isAsync = true;
  144. }
  145. if (isAsync) {
  146. try {
  147. if (optAttrDefined) {
  148. return await promisify(validator2.bind(this.modelInstance, invokeArgs))();
  149. }
  150. return await promisify(validator2.bind(this.modelInstance))();
  151. } catch (e) {
  152. return this._pushError(false, errorKey, e, optValue, validatorType);
  153. }
  154. }
  155. try {
  156. return await validator2.call(this.modelInstance, invokeArgs);
  157. } catch (e) {
  158. return this._pushError(false, errorKey, e, optValue, validatorType);
  159. }
  160. }
  161. async _invokeBuiltinValidator(value, test, validatorType, field) {
  162. const valueString = String(value);
  163. if (typeof validator[validatorType] !== "function") {
  164. throw new Error(`Invalid validator function: ${validatorType}`);
  165. }
  166. const validatorArgs = this._extractValidatorArgs(test, validatorType, field);
  167. if (!validator[validatorType](valueString, ...validatorArgs)) {
  168. throw Object.assign(new Error(test.msg || `Validation ${validatorType} on ${field} failed`), { validatorName: validatorType, validatorArgs });
  169. }
  170. }
  171. _extractValidatorArgs(test, validatorType, field) {
  172. let validatorArgs = test.args || test;
  173. const isLocalizedValidator = typeof validatorArgs !== "string" && ["isAlpha", "isAlphanumeric", "isMobilePhone"].includes(validatorType);
  174. if (!Array.isArray(validatorArgs)) {
  175. if (validatorType === "isImmutable") {
  176. validatorArgs = [validatorArgs, field, this.modelInstance];
  177. } else if (isLocalizedValidator || validatorType === "isIP") {
  178. validatorArgs = [];
  179. } else {
  180. validatorArgs = [validatorArgs];
  181. }
  182. } else {
  183. validatorArgs = validatorArgs.slice(0);
  184. }
  185. return validatorArgs;
  186. }
  187. _validateSchema(rawAttribute, field, value) {
  188. if (rawAttribute.allowNull === false && (value === null || value === void 0)) {
  189. const association = Object.values(this.modelInstance.constructor.associations).find((association2) => association2 instanceof BelongsTo && association2.foreignKey === rawAttribute.fieldName);
  190. if (!association || !this.modelInstance.get(association.associationAccessor)) {
  191. const validators = this.modelInstance.validators[field];
  192. const errMsg = _.get(validators, "notNull.msg", `${this.modelInstance.constructor.name}.${field} cannot be null`);
  193. this.errors.push(new sequelizeError.ValidationErrorItem(errMsg, "notNull Violation", field, value, this.modelInstance, "is_null"));
  194. }
  195. }
  196. if (rawAttribute.type instanceof DataTypes.STRING || rawAttribute.type instanceof DataTypes.TEXT || rawAttribute.type instanceof DataTypes.CITEXT) {
  197. if (Array.isArray(value) || _.isObject(value) && !(value instanceof Utils.SequelizeMethod) && !Buffer.isBuffer(value)) {
  198. this.errors.push(new sequelizeError.ValidationErrorItem(`${field} cannot be an array or an object`, "string violation", field, value, this.modelInstance, "not_a_string"));
  199. }
  200. }
  201. }
  202. _pushError(isBuiltin, errorKey, rawError, value, fnName, fnArgs) {
  203. const message = rawError.message || rawError || "Validation error";
  204. const error = new sequelizeError.ValidationErrorItem(message, "Validation error", errorKey, value, this.modelInstance, fnName, isBuiltin ? fnName : void 0, isBuiltin ? fnArgs : void 0);
  205. error[InstanceValidator.RAW_KEY_NAME] = rawError;
  206. this.errors.push(error);
  207. }
  208. }
  209. InstanceValidator.RAW_KEY_NAME = "original";
  210. module.exports = InstanceValidator;
  211. module.exports.InstanceValidator = InstanceValidator;
  212. module.exports.default = InstanceValidator;
  213. //# sourceMappingURL=instance-validator.js.map