Skip to content

Commit

Permalink
Added unique index check in insert
Browse files Browse the repository at this point in the history
  • Loading branch information
richardhodgson committed Jan 20, 2013
1 parent 69a029b commit 00c7ce7
Showing 1 changed file with 32 additions and 2 deletions.
34 changes: 32 additions & 2 deletions lib/mock/monk.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,16 @@ function Collection (name) {
this._name = name;
this._lastId = 0;
this._data = {};
this._indexes = {
'unique': []
};
}

Collection.prototype.index = function (property, type) {
if (! 'unique' in type) {
throw new Error("Mock monk only supports unique indexes");
}
this._indexes['unique'].push(property);
}

Collection.prototype.insert = function (ob, callback) {
Expand All @@ -45,8 +55,28 @@ Collection.prototype.insert = function (ob, callback) {
throw new Error("cannot insert object, _id already exists");
}

this._data[id] = dataSet;
promise.fulfill.call(promise, false, copy(dataSet));
var canInsert = true;
if (this._indexes['unique'].length > 0) {
var index = this._indexes['unique'],
unique = {};

for (var i = 0; i < index.length; i++) {
var property = index[i];
unique[property] = dataSet[property];
}

this.count(unique, function (err, results) {
if (results > 0) {
promise.emit('error', 'duplicate key error index: one of ' + index.join(','));
canInsert = false;
}
});
}

if (canInsert) {
this._data[id] = dataSet;
promise.fulfill.call(promise, false, copy(dataSet));
}
return promise;
}

Expand Down

0 comments on commit 00c7ce7

Please sign in to comment.