Added validation for embedded items (optional)

This commit is contained in:
Fabien Franzen 2014-07-27 16:54:01 +02:00
parent 59a957b538
commit 1487a592c1
2 changed files with 37 additions and 1 deletions

View File

@ -1422,6 +1422,29 @@ RelationDefinition.embedsMany = function hasMany(modelFrom, modelTo, params) {
}, { code: 'uniqueness' }) }, { code: 'uniqueness' })
} }
// validate all embedded items
if (definition.options.validate) {
modelFrom.validate(relationName, function(err) {
var embeddedList = this[relationName] || [];
var hasErrors = false;
embeddedList.forEach(function(item) {
if (item instanceof modelTo) {
if (!item.isValid()) {
hasErrors = true;
var first = Object.keys(item.errors)[0];
var msg = 'contains invalid item: `' + item[idName] + '`';
msg += ' (' + first + ' ' + item.errors[first] + ')';
this.errors.add(relationName, msg, 'invalid');
}
} else {
hasErrors = true;
this.errors.add(relationName, 'Contains invalid item', 'invalid');
}
}.bind(this));
if (hasErrors) err(false);
});
}
var scopeMethods = { var scopeMethods = {
findById: scopeMethod(definition, 'findById'), findById: scopeMethod(definition, 'findById'),
destroy: scopeMethod(definition, 'destroyById'), destroy: scopeMethod(definition, 'destroyById'),

View File

@ -1380,7 +1380,7 @@ describe('relations', function () {
}); });
it('can be declared', function (done) { it('can be declared', function (done) {
Person.embedsMany(Address, { options: { autoId: false } }); Person.embedsMany(Address, { options: { autoId: false, validate: true } });
db.automigrate(done); db.automigrate(done);
}); });
@ -1451,6 +1451,19 @@ describe('relations', function () {
}); });
}); });
it('should validate all embedded items', function(done) {
var addresses = [];
addresses.push({ id: 'home', street: 'Home Street' });
addresses.push({ id: 'work', street: '' });
Person.create({ name: 'Wilma', addresses: addresses }, function(err, p) {
err.name.should.equal('ValidationError');
var expected = 'The `Person` instance is not valid. ';
expected += 'Details: `addresses` contains invalid item: `work` (street can\'t be blank).';
err.message.should.equal(expected);
done();
});
});
}); });
}); });