Skip to content

Commit

Permalink
Throw error when trying to add model with same id
Browse files Browse the repository at this point in the history
Fixes #4
  • Loading branch information
SpaceK33z committed Mar 17, 2017
1 parent 6e74a07 commit 7257487
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 2 deletions.
11 changes: 9 additions & 2 deletions src/Store.js
Original file line number Diff line number Diff line change
Expand Up @@ -130,8 +130,15 @@ export default class Store {

const modelInstances = models.map(this._newModel.bind(this));

modelInstances.forEach(modelInstance =>
this.models.push(modelInstance));
modelInstances.forEach(modelInstance => {
const primaryValue = modelInstance[this.Model.primaryKey];
if (primaryValue && this.get(primaryValue)) {
throw Error(
`A model with the same primary key value "${primaryValue}" already exists in this store.`
);
}
this.models.push(modelInstance);
});

return singular ? modelInstances[0] : modelInstances;
}
Expand Down
42 changes: 42 additions & 0 deletions src/__tests__/Store.js
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,48 @@ test('add multiple models', () => {
expect(models[0]).toBeInstanceOf(Animal);
});

test('add multiple models with same id', () => {
const animalStore = new AnimalStore();
expect(() => {
return animalStore.add([
{
id: 20,
},
{
id: 20,
},
]);
}).toThrow(
'A model with the same primary key value "20" already exists in this store.'
);
});

test('add one model with existing id', () => {
const animalStore = new AnimalStore().parse(simpleData);
expect(() => {
return animalStore.add([
{
id: 3,
},
]);
}).toThrow(
'A model with the same primary key value "3" already exists in this store.'
);
});

test('add multiple models without id', () => {
const animalStore = new AnimalStore().parse(simpleData);
animalStore.add([
{
name: 'King',
},
{
name: 'Alfred',
},
]);
expect(animalStore.length).toBe(5);
});

test('clear models', () => {
const animalStore = new AnimalStore();
animalStore.parse(simpleData);
Expand Down

0 comments on commit 7257487

Please sign in to comment.