Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reject CREATE with a duplicate id #510

Merged
merged 2 commits into from Mar 19, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 7 additions & 0 deletions lib/connectors/memory.js
Expand Up @@ -210,6 +210,13 @@ Memory.prototype.create = function create(model, data, callback) {
if(!this.collection(model)) {
this.collection(model, {});
}

if (this.collection(model)[id]) {
return process.nextTick(function() {
callback(new Error('Duplicate entry for ' + model + '.' + idName));
});
}

this.collection(model)[id] = serialize(data);
this.saveToFile(id, callback);
};
Expand Down
2 changes: 1 addition & 1 deletion lib/dao.js
Expand Up @@ -393,7 +393,7 @@ DataAccessObject.updateOrCreate = DataAccessObject.upsert = function upsert(data
function done(err, data) {
var obj;
if (data && !(data instanceof Model)) {
inst._initProperties(data);
inst._initProperties(data, { persisted: true });
obj = inst;
} else {
obj = data;
Expand Down
28 changes: 28 additions & 0 deletions test/manipulation.test.js
Expand Up @@ -291,6 +291,25 @@ describe('manipulation', function () {
});
});

it('should refuse to create object with duplicate id', function(done) {
// NOTE(bajtos) We cannot reuse Person model here,
// `settings.forceId` aborts the CREATE request at the validation step.
var Product = db.define('Product', { name: String });
db.automigrate(function(err) {
if (err) return done(err);

Product.create({ name: 'a-name' }, function(err, p) {
if (err) return done(err);
Product.create({ id: p.id, name: 'duplicate' }, function(err) {
if (!err) {
return done(new Error('Create should have rejected duplicate id.'));
}
err.message.should.match(/duplicate/i);
done();
});
});
});
});
});

describe('save', function () {
Expand Down Expand Up @@ -548,6 +567,15 @@ describe('manipulation', function () {
});
});
});

it('should allow save() of the created instance', function(done) {
Person.updateOrCreate(
{ id: 'new-id', name: 'a-name' },
function(err, inst) {
if (err) return done(err);
inst.save(done);
});
});
});

describe('findOrCreate', function() {
Expand Down