Merge pull request #565 from strongloop/feature/validate-upsert
Validate model on updateOrCreate (upsert).
This commit is contained in:
commit
b642d52fbe
20
lib/dao.js
20
lib/dao.js
|
@ -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;
|
||||
|
|
|
@ -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');
|
||||
|
|
Loading…
Reference in New Issue