diff --git a/src/Store.js b/src/Store.js index 7ccea24..50f7976 100644 --- a/src/Store.js +++ b/src/Store.js @@ -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; } diff --git a/src/__tests__/Store.js b/src/__tests__/Store.js index 7ab6dd7..859af76 100644 --- a/src/__tests__/Store.js +++ b/src/__tests__/Store.js @@ -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);