Take strict: validate and throw settings into account

This commit is contained in:
Fabien Franzen 2015-07-21 13:33:42 +02:00
parent 8b06a9d39d
commit c7caa0a7c1
2 changed files with 51 additions and 4 deletions

View File

@ -2336,9 +2336,21 @@ DataAccessObject.prototype.updateAttributes = function updateAttributes(data, op
data = ctx.data;
if (strict) {
var keys = Object.keys(Model.definition.properties);
data = utils.selectFields(keys)(data);
data = removeUndefined(data);
var props = Model.definition.properties;
var keys = Object.keys(data);
var result = {};
for (var i = 0; i < keys.length; i++) {
key = keys[i];
if (props[key]) {
result[key] = data[key];
} else if (strict === 'throw') {
cb(new Error('Unknown property: ' + key));
return;
} else if (strict === 'validate') {
inst.__unknownProperties.push(key);
}
}
data = removeUndefined(result);
}
// update instance's properties

View File

@ -491,7 +491,7 @@ describe('manipulation', function () {
});
});
it('should ignore unknown attributes', function(done) {
it('should ignore unknown attributes when strict: true', function(done) {
person.updateAttributes({foo:'bar'},
function(err, p) {
if (err) return done(err);
@ -503,6 +503,41 @@ describe('manipulation', function () {
});
});
});
it('should throw error on unknown attributes when strict: throw', function(done) {
Person.definition.settings.strict = 'throw';
Person.findById(person.id, function(err, p) {
p.updateAttributes({foo:'bar'},
function(err, p) {
should.exist(err);
err.name.should.equal('Error');
err.message.should.equal('Unknown property: foo');
should.not.exist(p);
Person.findById(person.id, function(e, p) {
if (e) return done(e);
should.not.exist(p.foo);
done();
});
});
});
});
it('should throw error on unknown attributes when strict: throw', function(done) {
Person.definition.settings.strict = 'validate';
Person.findById(person.id, function(err, p) {
p.updateAttributes({foo:'bar'},
function(err, p) {
should.exist(err);
err.name.should.equal('ValidationError');
err.message.should.containEql('`foo` is not defined in the model');
Person.findById(person.id, function(e, p) {
if (e) return done(e);
should.not.exist(p.foo);
done();
});
});
});
});
it('should allow same id value on updateAttributes', function(done) {
person.updateAttributes({id: person.id, name: 'John'},