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

Commit 7ec60a7b by James Sapara

merged from rebased async-validations

1 parent 2f5415f8
Showing with 81 additions and 3 deletions
var Utils = require("./utils")
, Mixin = require("./associations/mixin")
, Validator = require("validator")
, DataTypes = require("./data-types")
, QueryChainer = require("./query-chainer")
, Validator = require("validator")
module.exports = (function() {
var DAO = function(values, options, isNewRecord) {
......@@ -256,14 +258,90 @@ module.exports = (function() {
}
}
return new Utils.CustomEventEmitter(function(emitter) {
var chainer = new QueryChainer;
// for each field and value
Utils._.each(self.values, function(value, field) {
// if field has validators
if (self.validators.hasOwnProperty(field)) {
// for each validator
Utils._.each(self.validators[field], function(details, validatorType) {
//var is_custom_fn = false // if true then it's a custom validation method
var fn_method = null // the validation function to call
var fn_args = [] // extra arguments to pass to validation function
var fn_msg = "" // the error message to return if validation fails
// is it a custom validator function?
if (Utils._.isFunction(details)) {
fn_method = function (next) {
//console.log(field, arguments);
details.apply(self, [value, next])
}
}
// is it a validator module function?
else {
// extra args
if (Utils._.isArray(details)) {
fn_args = Array.prototype.slice.call(details, 0);
} else {
fn_args = details.hasOwnProperty("args") ? details.args : []
}
if (!Utils._.isArray(fn_args))
fn_args = [fn_args]
// error msg
fn_msg = details.hasOwnProperty("msg") ? details.msg : false
// check method exists
var v = Validator.check(value, fn_msg)
if (!Utils._.isFunction(v[validatorType]))
throw new Error("Invalid validator function: " + validatorType)
fn_method = function (next) {
var args = Array.prototype.slice.call(arguments, 1);
try {
v[validatorType].apply(v, args);
next();
} catch (err) {
next(err.message);
}
}
}
chainer.add(new Utils.CustomEventEmitter(function(emitter) {
var next = function (err) {
if (err) {
var error = {};
error[field] = err;
emitter.emit('error', error);
} else {
emitter.emit('success')
}
}
fn_args.unshift(next);
fn_method.apply(self, fn_args)
}).run());
}) // for each validator for this field
} // if field has validator set
}) // for each field
return (Utils._.isEmpty(failures) ? null : failures)
chainer.run()
.error(function (err) {
var errors = {};
Utils._.each(err, function (value) {
Utils._.extend(errors, value);
});
emitter.emit('error', errors);
})
.success(function () {
emitter.emit('success');
})
}).run();
}
DAO.prototype.updateAttributes = function(updates, fields) {
this.setAttributes(updates)
return this.save(fields)
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!