Skip to content

Commit

Permalink
feat: add unique index support on create for in-memory connetor
Browse files Browse the repository at this point in the history
  • Loading branch information
biniam committed Dec 6, 2018
1 parent 5f713f0 commit 56d5418
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
14 changes: 14 additions & 0 deletions lib/connectors/memory.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ function Memory(m, settings) {
this.isTransaction = false;
this.cache = {};
this.ids = {};
this.indexes = {};
this.constructor.super_.call(this, 'memory', settings);
}
}
Expand Down Expand Up @@ -255,6 +256,19 @@ Memory.prototype._createSync = function(model, data, fn) {
this.collection(model, {});
}

for (var p in props) {
if (props[p].index && props[p].index.unique === true) {
for (var instId in this.cache[model]) {
var inst = JSON.parse(this.cache[model][instId]);
if (inst[p] === data[p]) {
var duplicateIndexError = new Error(g.f('Duplicate entry for %s.%s', model, p));
duplicateIndexError.statusCode = duplicateIndexError.status = 409;
return fn(duplicateIndexError);
}
}
}
}

if (this.collection(model)[id]) {
var error = new Error(g.f('Duplicate entry for %s.%s', model, idName));
error.statusCode = error.status = 409;
Expand Down
18 changes: 18 additions & 0 deletions test/memory.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -677,6 +677,24 @@ describe('Memory connector', function() {
});
});

it('should refuse to create object with duplicate unique index', function(done) {
var ds = new DataSource({connector: 'memory'});
var Product = ds.define('ProductTest', {name: {type: String, index: {unique: true}}}, {forceId: false});
ds.automigrate('ProductTest', function(err) {
if (err) return done(err);

Product.create({name: 'a-name'}, function(err, p) {
if (err) return done(err);
Product.create({name: 'a-name'}, function(err) {
should.exist(err);
err.message.should.match(/Duplicate/i);
err.statusCode.should.equal(409);
done();
});
});
});
});

describe('automigrate', function() {
var ds;
beforeEach(function() {
Expand Down

0 comments on commit 56d5418

Please sign in to comment.