不要怂,就是干,撸起袖子干!

Commit bf19d9a9 by Felix Becker Committed by Jan Aagaard Meier

ES6 refactor of instance-validator.js (#6044)

1 parent 797720d9
Showing with 101 additions and 104 deletions
'use strict'; 'use strict';
var validator = require('./utils/validator-extras').validator const validator = require('./utils/validator-extras').validator;
, extendModelValidations = require('./utils/validator-extras').extendModelValidations const extendModelValidations = require('./utils/validator-extras').extendModelValidations;
, Utils = require('./utils') const Utils = require('./utils');
, sequelizeError = require('./errors') const sequelizeError = require('./errors');
, Promise = require('./promise') const Promise = require('./promise');
, DataTypes = require('./data-types') const DataTypes = require('./data-types');
, _ = require('lodash'); const _ = require('lodash');
/** /**
* The Main Instance Validator. * The Main Instance Validator.
...@@ -15,7 +15,9 @@ var validator = require('./utils/validator-extras').validator ...@@ -15,7 +15,9 @@ var validator = require('./utils/validator-extras').validator
* @param {Object} options A dict with options. * @param {Object} options A dict with options.
* @constructor * @constructor
*/ */
var InstanceValidator = module.exports = function(modelInstance, options) { class InstanceValidator {
constructor(modelInstance, options) {
options = _.clone(options) || {}; options = _.clone(options) || {};
if (options.fields && !options.skip) { if (options.fields && !options.skip) {
...@@ -47,36 +49,29 @@ var InstanceValidator = module.exports = function(modelInstance, options) { ...@@ -47,36 +49,29 @@ var InstanceValidator = module.exports = function(modelInstance, options) {
this.inProgress = false; this.inProgress = false;
extendModelValidations(modelInstance); extendModelValidations(modelInstance);
}; }
/** @define {string} The error key for arguments as passed by custom validators */
InstanceValidator.RAW_KEY_NAME = '__raw';
/** /**
* The main entry point for the Validation module, invoke to start the dance. * The main entry point for the Validation module, invoke to start the dance.
* *
* @return {Promise} * @return {Promise}
*/ */
InstanceValidator.prototype._validate = function() { _validate() {
if (this.inProgress) { if (this.inProgress) {
throw new Error('Validations already in progress.'); throw new Error('Validations already in progress.');
} }
this.inProgress = true; this.inProgress = true;
var self = this; return Promise.all(
return Promise.all([ [this._builtinValidators(), this._customValidators()].map(promise => promise.reflect())
self._builtinValidators(), ).then(() => {
self._customValidators() if (this.errors.length) {
].map(function(promise) { throw new sequelizeError.ValidationError(null, this.errors);
return promise.reflect();
})).then(function() {
if (self.errors.length) {
throw new sequelizeError.ValidationError(null, self.errors);
} }
}); });
}; }
/** /**
* Invoke the Validation sequence: * Invoke the Validation sequence:
* - Before Validation Model Hooks * - Before Validation Model Hooks
* - Validation * - Validation
...@@ -85,79 +80,76 @@ InstanceValidator.prototype._validate = function() { ...@@ -85,79 +80,76 @@ InstanceValidator.prototype._validate = function() {
* *
* @return {Promise} * @return {Promise}
*/ */
InstanceValidator.prototype.validate = function() { validate() {
if (this.options.hooks) { if (this.options.hooks) {
return this.modelInstance.constructor.runHooks('beforeValidate', this.modelInstance, this.options).bind(this).then(function() { return this.modelInstance.constructor.runHooks('beforeValidate', this.modelInstance, this.options)
return this._validate().bind(this).catch(function(error) { .then(() =>
return this.modelInstance.constructor.runHooks('validationFailed', this.modelInstance, this.options, error).then(function(newError) { this._validate().catch(error =>
this.modelInstance.constructor.runHooks('validationFailed', this.modelInstance, this.options, error).then(newError => {
throw newError || error; throw newError || error;
}); })
}); )
}).then(function() { )
return this.modelInstance.constructor.runHooks('afterValidate', this.modelInstance, this.options); .then(() => this.modelInstance.constructor.runHooks('afterValidate', this.modelInstance, this.options))
}).return(this.modelInstance); .return(this.modelInstance);
} }
return this._validate(); return this._validate();
}
}; /**
/**
* Will run all the built-in validators. * Will run all the built-in validators.
* *
* @return {Promise(Array.<Promise.PromiseInspection>)} A promise from .reflect(). * @return {Promise(Array.<Promise.PromiseInspection>)} A promise from .reflect().
* @private * @private
*/ */
InstanceValidator.prototype._builtinValidators = function() { _builtinValidators() {
var self = this;
// promisify all attribute invocations // promisify all attribute invocations
var validators = []; const validators = [];
Utils._.forIn(this.modelInstance.rawAttributes, function(rawAttribute, field) { Utils._.forIn(this.modelInstance.rawAttributes, (rawAttribute, field) => {
if (self.options.skip.indexOf(field) >= 0) { if (this.options.skip.indexOf(field) >= 0) {
return; return;
} }
var value = self.modelInstance.dataValues[field]; const value = this.modelInstance.dataValues[field];
if (!rawAttribute._autoGenerated && !rawAttribute.autoIncrement) { if (!rawAttribute._autoGenerated && !rawAttribute.autoIncrement) {
// perform validations based on schema // perform validations based on schema
self._validateSchema(rawAttribute, field, value); this._validateSchema(rawAttribute, field, value);
} }
if (self.modelInstance.validators.hasOwnProperty(field)) { if (this.modelInstance.validators.hasOwnProperty(field)) {
validators.push(self._builtinAttrValidate.call(self, value, field).reflect()); validators.push(this._builtinAttrValidate.call(this, value, field).reflect());
} }
}); });
return Promise.all(validators); return Promise.all(validators);
}; }
/** /**
* Will run all the custom validators. * Will run all the custom validators.
* *
* @return {Promise(Array.<Promise.PromiseInspection>)} A promise from .reflect(). * @return {Promise(Array.<Promise.PromiseInspection>)} A promise from .reflect().
* @private * @private
*/ */
InstanceValidator.prototype._customValidators = function() { _customValidators() {
var validators = []; const validators = [];
var self = this; Utils._.each(this.modelInstance.$modelOptions.validate, (validator, validatorType) => {
Utils._.each(this.modelInstance.$modelOptions.validate, function(validator, validatorType) { if (this.options.skip.indexOf(validatorType) >= 0) {
if (self.options.skip.indexOf(validatorType) >= 0) {
return; return;
} }
var valprom = self._invokeCustomValidator(validator, validatorType) const valprom = this._invokeCustomValidator(validator, validatorType)
// errors are handled in settling, stub this // errors are handled in settling, stub this
.catch(function() {}) .catch(() => {})
.reflect(); .reflect();
validators.push(valprom); validators.push(valprom);
}); });
return Promise.all(validators); return Promise.all(validators);
}; }
/** /**
* Validate a single attribute with all the defined built-in validators. * Validate a single attribute with all the defined built-in validators.
* *
* @param {*} value Anything. * @param {*} value Anything.
...@@ -166,17 +158,15 @@ InstanceValidator.prototype._customValidators = function() { ...@@ -166,17 +158,15 @@ InstanceValidator.prototype._customValidators = function() {
* auto populates error on this.error local object. * auto populates error on this.error local object.
* @private * @private
*/ */
InstanceValidator.prototype._builtinAttrValidate = function(value, field) { _builtinAttrValidate(value, field) {
var self = this;
// check if value is null (if null not allowed the Schema pass will capture it) // check if value is null (if null not allowed the Schema pass will capture it)
if (value === null || typeof value === 'undefined') { if (value === null || typeof value === 'undefined') {
return Promise.resolve(); return Promise.resolve();
} }
// Promisify each validator // Promisify each validator
var validators = []; const validators = [];
Utils._.forIn(this.modelInstance.validators[field], function(test, Utils._.forIn(this.modelInstance.validators[field], (test, validatorType) => {
validatorType) {
if (['isUrl', 'isURL', 'isEmail'].indexOf(validatorType) !== -1) { if (['isUrl', 'isURL', 'isEmail'].indexOf(validatorType) !== -1) {
// Preserve backwards compat. Validator.js now expects the second param to isURL and isEmail to be an object // Preserve backwards compat. Validator.js now expects the second param to isURL and isEmail to be an object
...@@ -191,19 +181,19 @@ InstanceValidator.prototype._builtinAttrValidate = function(value, field) { ...@@ -191,19 +181,19 @@ InstanceValidator.prototype._builtinAttrValidate = function(value, field) {
// Check for custom validator. // Check for custom validator.
if (typeof test === 'function') { if (typeof test === 'function') {
return validators.push(self._invokeCustomValidator(test, validatorType, true, value, field).reflect()); return validators.push(this._invokeCustomValidator(test, validatorType, true, value, field).reflect());
} }
var validatorPromise = self._invokeBuiltinValidator(value, test, validatorType, field); const validatorPromise = this._invokeBuiltinValidator(value, test, validatorType, field);
// errors are handled in settling, stub this // errors are handled in settling, stub this
validatorPromise.catch(function() {}); validatorPromise.catch(() => {});
validators.push(validatorPromise.reflect()); validators.push(validatorPromise.reflect());
}); });
return Promise.all(validators).then(this._handleReflectedResult.bind(this, field)); return Promise.all(validators).then(this._handleReflectedResult.bind(this, field));
}; }
/** /**
* Prepare and invoke a custom validator. * Prepare and invoke a custom validator.
* *
* @param {Function} validator The custom validator. * @param {Function} validator The custom validator.
...@@ -213,15 +203,15 @@ InstanceValidator.prototype._builtinAttrValidate = function(value, field) { ...@@ -213,15 +203,15 @@ InstanceValidator.prototype._builtinAttrValidate = function(value, field) {
* @return {Promise} A promise. * @return {Promise} A promise.
* @private * @private
*/ */
InstanceValidator.prototype._invokeCustomValidator = Promise.method(function(validator, validatorType, optAttrDefined, optValue, optField) { _invokeCustomValidator(validator, validatorType, optAttrDefined, optValue, optField) {
var validatorFunction = null; // the validation function to call let validatorFunction = null; // the validation function to call
var isAsync = false; let isAsync = false;
var validatorArity = validator.length; const validatorArity = validator.length;
// check if validator is async and requires a callback // check if validator is async and requires a callback
var asyncArity = 1; let asyncArity = 1;
var errorKey = validatorType; let errorKey = validatorType;
var invokeArgs; let invokeArgs;
if (optAttrDefined) { if (optAttrDefined) {
asyncArity = 2; asyncArity = 2;
invokeArgs = optValue; invokeArgs = optValue;
...@@ -241,9 +231,9 @@ InstanceValidator.prototype._invokeCustomValidator = Promise.method(function(val ...@@ -241,9 +231,9 @@ InstanceValidator.prototype._invokeCustomValidator = Promise.method(function(val
} else { } else {
return Promise.try(validator.bind(this.modelInstance, invokeArgs)).catch(this._pushError.bind(this, false, errorKey)); return Promise.try(validator.bind(this.modelInstance, invokeArgs)).catch(this._pushError.bind(this, false, errorKey));
} }
}); }
/** /**
* Prepare and invoke a build-in validator. * Prepare and invoke a build-in validator.
* *
* @param {*} value Anything. * @param {*} value Anything.
...@@ -253,22 +243,23 @@ InstanceValidator.prototype._invokeCustomValidator = Promise.method(function(val ...@@ -253,22 +243,23 @@ InstanceValidator.prototype._invokeCustomValidator = Promise.method(function(val
* @return {Object} An object with specific keys to invoke the validator. * @return {Object} An object with specific keys to invoke the validator.
* @private * @private
*/ */
InstanceValidator.prototype._invokeBuiltinValidator = Promise.method(function(value, test, validatorType, field) { _invokeBuiltinValidator(value, test, validatorType, field) {
var self = this; return Promise.try(() => {
// Cast value as string to pass new Validator.js string requirement // Cast value as string to pass new Validator.js string requirement
var valueString = String(value); const valueString = String(value);
// check if Validator knows that kind of validation test // check if Validator knows that kind of validation test
if (typeof validator[validatorType] !== 'function') { if (typeof validator[validatorType] !== 'function') {
throw new Error('Invalid validator function: ' + validatorType); throw new Error('Invalid validator function: ' + validatorType);
} }
var validatorArgs = self._extractValidatorArgs(test, validatorType, field); const validatorArgs = this._extractValidatorArgs(test, validatorType, field);
if (!validator[validatorType].apply(validator, [valueString].concat(validatorArgs))) { if (!validator[validatorType].apply(validator, [valueString].concat(validatorArgs))) {
// extract the error msg // extract the error msg
throw new Error(test.msg || 'Validation ' + validatorType + ' failed'); throw new Error(test.msg || 'Validation ' + validatorType + ' failed');
} }
}); });
}
/** /**
* Will extract arguments for the validator. * Will extract arguments for the validator.
* *
* @param {*} test The test case. * @param {*} test The test case.
...@@ -276,9 +267,9 @@ InstanceValidator.prototype._invokeBuiltinValidator = Promise.method(function(va ...@@ -276,9 +267,9 @@ InstanceValidator.prototype._invokeBuiltinValidator = Promise.method(function(va
* @param {string} field The field that is being validated. * @param {string} field The field that is being validated.
* @private * @private
*/ */
InstanceValidator.prototype._extractValidatorArgs = function(test, validatorType, field) { _extractValidatorArgs(test, validatorType, field) {
var validatorArgs = test.args || test; let validatorArgs = test.args || test;
var isLocalizedValidator = typeof(validatorArgs) !== 'string' && (validatorType === 'isAlpha' || validatorType === 'isAlphanumeric' || validatorType === 'isMobilePhone'); const isLocalizedValidator = typeof(validatorArgs) !== 'string' && (validatorType === 'isAlpha' || validatorType === 'isAlphanumeric' || validatorType === 'isMobilePhone');
if (!Array.isArray(validatorArgs)) { if (!Array.isArray(validatorArgs)) {
if (validatorType === 'isImmutable') { if (validatorType === 'isImmutable') {
...@@ -292,9 +283,9 @@ InstanceValidator.prototype._extractValidatorArgs = function(test, validatorType ...@@ -292,9 +283,9 @@ InstanceValidator.prototype._extractValidatorArgs = function(test, validatorType
validatorArgs = validatorArgs.slice(0); validatorArgs = validatorArgs.slice(0);
} }
return validatorArgs; return validatorArgs;
}; }
/** /**
* Will validate a single field against its schema definition (isnull). * Will validate a single field against its schema definition (isnull).
* *
* @param {Object} rawAttribute As defined in the Schema. * @param {Object} rawAttribute As defined in the Schema.
...@@ -302,8 +293,8 @@ InstanceValidator.prototype._extractValidatorArgs = function(test, validatorType ...@@ -302,8 +293,8 @@ InstanceValidator.prototype._extractValidatorArgs = function(test, validatorType
* @param {*} value anything. * @param {*} value anything.
* @private * @private
*/ */
InstanceValidator.prototype._validateSchema = function(rawAttribute, field, value) { _validateSchema(rawAttribute, field, value) {
var error; let error;
if (rawAttribute.allowNull === false && ((value === null) || (value === undefined))) { if (rawAttribute.allowNull === false && ((value === null) || (value === undefined))) {
error = new sequelizeError.ValidationErrorItem(field + ' cannot be null', 'notNull Violation', field, value); error = new sequelizeError.ValidationErrorItem(field + ' cannot be null', 'notNull Violation', field, value);
...@@ -316,10 +307,10 @@ InstanceValidator.prototype._validateSchema = function(rawAttribute, field, valu ...@@ -316,10 +307,10 @@ InstanceValidator.prototype._validateSchema = function(rawAttribute, field, valu
this.errors.push(error); this.errors.push(error);
} }
} }
}; }
/** /**
* Handles the returned result of a Promise.reflect. * Handles the returned result of a Promise.reflect.
* *
* If errors are found it populates this.error. * If errors are found it populates this.error.
...@@ -328,17 +319,16 @@ InstanceValidator.prototype._validateSchema = function(rawAttribute, field, valu ...@@ -328,17 +319,16 @@ InstanceValidator.prototype._validateSchema = function(rawAttribute, field, valu
* @param {Array.<Promise.PromiseInspection>} Promise inspection objects. * @param {Array.<Promise.PromiseInspection>} Promise inspection objects.
* @private * @private
*/ */
InstanceValidator.prototype._handleReflectedResult = function(field, promiseInspections) { _handleReflectedResult(field, promiseInspections) {
var self = this; for (const promiseInspection of promiseInspections) {
promiseInspections.forEach(function(promiseInspection) {
if (promiseInspection.isRejected()) { if (promiseInspection.isRejected()) {
var rejection = promiseInspection.error(); const rejection = promiseInspection.error();
self._pushError(true, field, rejection); this._pushError(true, field, rejection);
}
}
} }
});
};
/** /**
* Signs all errors retaining the original. * Signs all errors retaining the original.
* *
* @param {boolean} isBuiltin Determines if error is from builtin validator. * @param {boolean} isBuiltin Determines if error is from builtin validator.
...@@ -346,10 +336,17 @@ InstanceValidator.prototype._handleReflectedResult = function(field, promiseInsp ...@@ -346,10 +336,17 @@ InstanceValidator.prototype._handleReflectedResult = function(field, promiseInsp
* @param {Error|string} rawError The original error. * @param {Error|string} rawError The original error.
* @private * @private
*/ */
InstanceValidator.prototype._pushError = function(isBuiltin, errorKey, rawError) { _pushError(isBuiltin, errorKey, rawError) {
var message = rawError.message || rawError || 'Validation error'; const message = rawError.message || rawError || 'Validation error';
var error = new sequelizeError.ValidationErrorItem(message, 'Validation error', errorKey, rawError); const error = new sequelizeError.ValidationErrorItem(message, 'Validation error', errorKey, rawError);
error[InstanceValidator.RAW_KEY_NAME] = rawError; error[InstanceValidator.RAW_KEY_NAME] = rawError;
this.errors.push(error); this.errors.push(error);
}; }
}
/** @define {string} The error key for arguments as passed by custom validators */
InstanceValidator.RAW_KEY_NAME = '__raw';
module.exports = InstanceValidator;
module.exports.InstanceValidator = InstanceValidator;
module.exports.default = InstanceValidator;
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!