Validate model on updateOrCreate (upsert).

Fix the implementation of updateOrCreate (a.k.a. upsert) to validate
the model before calling the connector.

In order to preserve backwards compatibility, validation errors are
only logged via console.warn by default.

The correct behaviour, where validation errors fail the updateOrCreate
operation, can be enabled via new model setting "validateUpsert".
This commit is contained in:
Miroslav Bajtoš 2015-04-16 09:03:56 +02:00
parent dc54d02485
commit 3df62444d6
2 changed files with 36 additions and 5 deletions

View File

@ -403,12 +403,22 @@ DataAccessObject.updateOrCreate = DataAccessObject.upsert = function upsert(data
Model.applyProperties(update, inst);
Model = Model.lookupModel(update);
// FIXME(bajtos) validate the model!
// https://github.com/strongloop/loopback-datasource-juggler/issues/262
inst.isValid(function(valid) {
if (!valid) {
// TODO(bajtos) Remove validateUpsert option in v3.0
if (Model.settings.validateUpsert) {
return cb(new ValidationError(inst), inst);
} else {
console.warn('Ignoring validation errors in updateOrCreate():');
console.warn(' %s', new ValidationError(inst).message);
// continue with updateOrCreate
}
}
update = removeUndefined(update);
self.getDataSource().connector
.updateOrCreate(Model.modelName, update, done);
update = removeUndefined(update);
self.getDataSource().connector
.updateOrCreate(Model.modelName, update, done);
}, update);
function done(err, data, info) {
var obj;

View File

@ -184,6 +184,27 @@ describe('validations', function () {
});
});
it('should be skipped on upsert by default', function(done) {
delete User.validations;
User.validatesPresenceOf('name');
// It's important to pass an id value, otherwise DAO falls back
// to regular create()
User.updateOrCreate({ id: 999 }, done);
});
it('should work on upsert when enabled via settings', function(done) {
delete User.validations;
User.validatesPresenceOf('name');
User.settings.validateUpsert = true;
// It's important to pass an id value, otherwise DAO falls back
// to regular create()
User.upsert({ id: 999 }, function(err, u) {
if (!err) return done(new Error('Validation should have failed.'));
err.should.be.instanceOf(ValidationError);
done();
});
});
it('should return error code', function (done) {
delete User.validations;
User.validatesPresenceOf('name');