Fix forceId validation error

This commit is contained in:
Loay 2017-01-04 11:33:49 -05:00
parent ae07480f45
commit 44a5a7ad81
3 changed files with 55 additions and 1 deletions

View File

@ -793,7 +793,9 @@ Memory.prototype.replaceById = function(model, id, data, options, cb) {
var modelData = cachedModels && this.collection(model)[id];
if (!modelData) {
var msg = 'Could not replace. Object with id ' + id + ' does not exist!';
return process.nextTick(function() { cb(new Error(msg)); });
var error = new Error(msg);
error.statusCode = error.status = 404;
return process.nextTick(function() { cb(error); });
}
var newModelData = {};

View File

@ -840,6 +840,11 @@ DataAccessObject.replaceOrCreate = function replaceOrCreate(data, options, cb) {
return this.create(data, options, cb);
}
var forceId = this.settings.forceId;
if (forceId) {
return Model.replaceById(id, data, options, cb);
}
var inst;
if (data instanceof Model) {
inst = data;

View File

@ -12,6 +12,7 @@ var should = require('./init.js');
var db, Person;
var ValidationError = require('..').ValidationError;
var bdd = require('./helpers/bdd-if.js');
var UUID_REGEXP = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
@ -1097,6 +1098,52 @@ describe('manipulation', function() {
});
}
var hasReplaceById = !!getSchema().connector.replaceById;
bdd.describeIf(hasReplaceById, 'replaceOrCreate when forceId is true', function() {
var Post;
before(function(done) {
var ds = getSchema();
Post = ds.define('Post', {
title: {type: String, length: 255},
content: {type: String},
}, {forceId: true});
ds.automigrate('Post', done);
});
it('fails when id does not exist in db', function(done) {
var post = {id: 123, title: 'a', content: 'AAA'};
Post.replaceOrCreate(post, function(err, p) {
err.statusCode.should.equal(404);
done();
});
});
it('works on create if the request does not include an id', function(done) {
var post = {title: 'a', content: 'AAA'};
Post.replaceOrCreate(post, function(err, p) {
if (err) return done(err);
p.title.should.equal(post.title);
p.content.should.equal(post.content);
done();
});
});
it('works on update if the request includes an existing id in db', function(done) {
Post.create({title: 'a', content: 'AAA'},
function(err, post) {
if (err) return done(err);
post = post.toObject();
delete post.content;
post.title = 'b';
Post.replaceOrCreate(post, function(err, p) {
if (err) return done(err);
p.id.should.equal(post.id);
done();
});
});
});
});
if (!getSchema().connector.replaceById) {
describe.skip('replaceAttributes/replaceById - not implemented', function() {});
} else {