From e7b462273ca6ff370fd04c649ed6551e15795025 Mon Sep 17 00:00:00 2001 From: Pau Ramon Revilla Date: Thu, 13 Jul 2017 10:52:13 +0200 Subject: [PATCH] 2.2.1 - Add `reset` method --- CHANGELOG.md | 6 ++++++ README.md | 16 ++++++++++++++-- __tests__/Collection.spec.js | 10 ++++++++++ package.json | 2 +- src/Collection.js | 11 +++++++++++ 5 files changed, 42 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f556654..f294958 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog +## `2.2.1` + +:tophat: + + - Added `reset` for conveniently resetting a whole collection + ## `2.2.0` :nail_care: diff --git a/README.md b/README.md index 6170a9e..6231e44 100644 --- a/README.md +++ b/README.md @@ -307,9 +307,21 @@ const pau = usersCollection.find({ name: 'pau' }) pau.get('name') // => 'pau' ``` -#### `add(data: Object): Array` +#### `add(data: Array): Array` -Add a model with the given attributes. +Adds models with the given array of attributes. + +```js +usersCollection.add([{id: 1, name: 'foo'}]) +``` + +#### `reset(data: Array): Array` + +Resets the collection with the given models. + +```js +usersCollection.reset([{id: 1, name: 'foo'}]) +``` #### `remove(ids: Array): void` diff --git a/__tests__/Collection.spec.js b/__tests__/Collection.spec.js index 5c93942..d32fae0 100644 --- a/__tests__/Collection.spec.js +++ b/__tests__/Collection.spec.js @@ -98,6 +98,16 @@ describe('Collection', () => { }) }) + describe('reset', () => { + it('reset a collection of models', () => { + const newItem = { id: 2, name: 'bob' } + collection.reset([newItem]) + + expect(collection.models.length).toBe(1) + expect(collection.get(2).get('name')).toBe(newItem.name) + }) + }) + describe('remove', () => { it('removes a collection of models', () => { collection.remove([1]) diff --git a/package.json b/package.json index 32d264f..c9ef033 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "mobx-rest", - "version": "2.2.0", + "version": "2.2.1", "description": "REST conventions for mobx.", "repository": { "type": "git", diff --git a/src/Collection.js b/src/Collection.js index 450ba73..e4e59ad 100644 --- a/src/Collection.js +++ b/src/Collection.js @@ -149,6 +149,17 @@ export default class Collection { return models } + /** + * Resets a collection of models. + * Returns the added models. + */ + @action + reset (data: Array<{ [key: string]: any }>): Array { + const models = data.map(d => this.build(d)) + this.models = models + return models + } + /** * Removes the model with the given ids or uuids */