dataflux 1.2.2 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2022 Massimo Candela
3
+ Copyright (c) 2022-present Massimo Candela
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -30,23 +30,34 @@ Create your global store by creating a file (e.g., named `store.js`) containing
30
30
  Consider the following hypothetical store/model declaration common to all the examples below:
31
31
 
32
32
  ```js
33
+ // Content of your store.js
33
34
  import {Store, Model} from "dataflux";
34
35
 
36
+ // We create a new Store
35
37
  const store = new Store();
36
- const author = new Model("author", `https://rest.example.net/api/v1/authors`);
37
- const book = new Model("book", `https://rest.example.net/api/v1/books`);
38
38
 
39
- store.addModel(author);
39
+ // We now create two models, "author" and "book".
40
+ // Both of them are auto generated based on the output of a REST API.
41
+ // The REST API does NOT need to provide a specific format.
42
+ // E.g., /books returns [{"title": "Hamlet", "year": 1600}, ...].
43
+ // See "REST API format" below for more info.
44
+ const book = new Model("book", `https://api.example.net/books`);
45
+ const author = new Model("author", `https://api.example.net/authors`);
46
+
47
+ // We add the models to the store
40
48
  store.addModel(book);
49
+ store.addModel(author);
41
50
 
42
- // An object relation between author.id and book.authorId as follows
51
+ // Optionally, we can declare relations among models.
52
+ // E.g., we can declare that an author has one or more books.
43
53
  author.addRelation(book, "id", "authorId");
54
+ // The relation will provide all the books where author.id = book.authorId
44
55
 
45
56
  export default store;
46
57
  ```
47
58
 
48
59
 
49
- The store can be initialized with [various options](#configuration). You need only one store for the entire application, that's why you should declare it in its own file and import it in multiple places.
60
+ The store can be initialized with [various options](#configuration). You need only one store for the entire application, that's why you should declare it in its own file (store.js in this case) and import it in multiple places.
50
61
 
51
62
  The creation of a model requires at least a name and a url. GET, POST, PUT, and DELETE operations are going to be performed against the same url. [Models can be created with considerably more advanced options.](#models-creation)
52
63
 
@@ -55,28 +66,31 @@ A JS object is automatically created for each item returned by the API, for each
55
66
 
56
67
  ### Example 1
57
68
 
58
- Retrieve and edit an author not knowing the ID:
69
+ Retrieve and edit an author by name and surname:
59
70
 
60
71
  ```js
61
- import store from "./store";
72
+ import store from "./store"; // Import our store.js
62
73
 
63
74
  // Find the author Dante Alighieri
64
75
  store.find("author", ({name, surname}) => name == "Dante" && surname == "Alighieri")
65
76
  .then(([author]) => {
77
+
78
+ // We got the author, let's now edit it
66
79
  author.set("country", "Italy");
67
80
  author.set("type", "poet");
68
- // Nothing else to do, the store does a single PUT request to the model's API about the edited object
69
81
  });
70
82
  ```
71
83
 
72
- > You don't necessarily need to use `object.set` to edit an object attribute. You could do `author.country = "Italy"`. However, this approach relies on a periodic detection of changes (while `.set` triggers an update immediately). Check the `autoSave` option for more information
84
+ Nothing else to do! After your edit, the store will do a single PUT request to the model's API to save the edited object. This behavior can be disabled, see next example.
85
+
86
+ > You don't necessarily need to use `object.set` to edit an object attribute. You could do `author.country = "Italy"`. However, this approach has disadvantages, read [editing objects](#editing-objects) for more information
73
87
 
74
88
  ### Example 2
75
89
 
76
- Operations without autoSave:
90
+ DataFlux automatically sends the edited objects back to the API to be saved. However, you can disable this behavior and manually instruct the store when to save.
77
91
 
78
92
  ```js
79
- // To disable autoSave you must declare the store as follows
93
+ // To disable autoSave you must declare the store (in store.js) as follows
80
94
  const store = new Store({autoSave: false});
81
95
  ```
82
96
 
@@ -86,11 +100,13 @@ The same example above now becomes:
86
100
  // Find the author Dante Alighieri
87
101
  store.find("author", ({name, surname}) => name == "Dante" && surname == "Alighieri")
88
102
  .then(([author]) => {
89
- // When autoSave = false, you can still use author.set, but there is no actual benefit
103
+
104
+ // When autoSave is false, author.set("country", "Italy") and
105
+ // author.country = "Italy" are equivalent
90
106
  author.country = "Italy"
91
107
  author.type = "poet"
92
108
 
93
- store.save(); // Even if we changed only one author, prefer always store.save() to author.save()
109
+ store.save(); // Instruct the store to save
94
110
  });
95
111
  ```
96
112
 
@@ -129,6 +145,7 @@ author.getRelation("book");
129
145
 
130
146
  If you use `subscribe` instead of `find`, you can provide a callback to be invoked when data is ready or there is a change in the data.
131
147
 
148
+ _**DataFlux remembers your query and calls your callback every time any change is affecting the result of your query!**_
132
149
 
133
150
  ```js
134
151
  const drawBooksCallback = (books) => {
@@ -139,7 +156,7 @@ const drawBooksCallback = (books) => {
139
156
  store.subscribe("book", drawBooks, ({price}) => price < 20);
140
157
  ```
141
158
 
142
- If now somewhere a book is inserted/deleted/edited:
159
+ If now a book is inserted/deleted/edited:
143
160
  * if the book has `price < 20`, `drawBooksCallback` will be called again with the new dataset;
144
161
  * if the book has `price > 20`, `drawBooksCallback` will NOT be called again (because the new book doesn't impact our selection).
145
162
 
@@ -151,14 +168,31 @@ const subKey = store.subscribe("book", drawBooks, ({price}) => price < 20); // S
151
168
  store.unsubscribe(subKey); // Unsubscribe
152
169
  ```
153
170
 
171
+ You can also do multiple subscriptions at once:
172
+
173
+ ```js
174
+ const subscriptions = [
175
+ ["book", ({title}) => title === "The little prince"], // Model name and filter function
176
+ ["author"], // No filter function, all objects returned
177
+ ];
178
+
179
+ const callback = ([books, authors]) => {
180
+ // Objects are ready
181
+ };
182
+
183
+ const subKey = store.multipleSubscribe(requests, callback); // Subscribe
184
+
185
+ store.unsubscribe(subKey); // Unsubscribe
186
+ ```
187
+
154
188
  ### Example 6 - Observability + React
155
189
 
156
190
  The integration with React is offered transparently when using the store inside a `React.Component`.
157
- You can use two methods: `findOne`, and `findAll`.
191
+ You can use two methods: `findOne`, and `findAll` (which are a react-specific syntactic sugar over `subscribe`).
158
192
 
159
- > Since the store is able to detect changes deep in a nested structure, you will not have to worry about the component not re-rendering. Also, the setState will only be triggered when the next change of the dataset is really impacting your selection.
193
+ **_Since the store is able to detect changes deep in a nested structure, you will not have to worry about the component not re-rendering. Also, the setState will be triggered ONLY when the next change of the dataset is impacting your selection._**
160
194
 
161
- React Component example
195
+ React Component example:
162
196
  ```jsx
163
197
  class MyComponent extends React.Component {
164
198
  constructor(props) {
@@ -168,9 +202,9 @@ class MyComponent extends React.Component {
168
202
  componentDidMount() {
169
203
  // Get all books with a price < 20
170
204
  store.findAll("book", "books", this, ({price}) => price < 20);
171
- // Every time the dataset changes, a setState will be automatically
172
- // performed. An attribute "books" will be added/updated in the
173
- // state (the rest of the state remains unchanged).
205
+ // An attribute "books" will be added/updated in the
206
+ // state (the rest of the state remains unchanged) every time
207
+ // a book in our selection is inserted/deleted/edited.
174
208
 
175
209
  // findAll is a syntactic sugar for:
176
210
  // const callback = (books) => {this.setState({...this.state, books})};
@@ -185,7 +219,7 @@ class MyComponent extends React.Component {
185
219
  onTitleChange={(title) => book.set("title", title)}
186
220
  // onTitleChange will alter the book and so the current
187
221
  // state of "books" (a setState will be performed).
188
- //
222
+
189
223
  // Alternatively:
190
224
  // onTitleChange={store.handleChange(book, "title")}
191
225
  // is a syntactic sugar of the function above
@@ -194,9 +228,9 @@ class MyComponent extends React.Component {
194
228
  }
195
229
  ```
196
230
 
197
- The method `findAll` returns always an array. The method `findOne` returns a single object (if multiple objects satisfy the search, the first is returned).
231
+ The method `findAll` returns always an array. The method `findOne` returns a single object (if multiple objects satisfy the query, the first is returned).
198
232
 
199
- When the component will unmount, the `findAll` subscription will be automatically terminated without the need to unsubscribe. Be aware, `store.findAll` injects the unsubscribe call inside `componentWillUnmount`. If your component already implements `componentWillUnmount()`, then you will have to use `store.subscribe` and `store.unsubscribe` instead of `store.findAll`, to avoid side effects when the component is unmounted.
233
+ When the component will unmount, the `findAll` subscription will be automatically terminated without the need to unsubscribe. Be aware, `store.findAll()` injects the unsubscribe call inside `componentWillUnmount()`. If your component already implements `componentWillUnmount()`, then you will have to use `store.subscribe()` and `store.unsubscribe()` instead of `store.findAll()`, to avoid side effects when the component is unmounted.
200
234
 
201
235
  ## Configuration
202
236
 
@@ -205,7 +239,7 @@ The store can be configured with the following options:
205
239
 
206
240
  | Option | Description | Default |
207
241
  |-----------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------|
208
- | autoSave | It can be `true`, `false`, or an amount of milliseconds (integer). If `false`, you will have to perform `store.save()` manually. If `true`, the store will automatically perform `save()` when objects change. If an amount of milliseconds is provided, the objects are saved periodically AND when a change is detected. See [Editing objects](#editing-objects) for more information. | 3000 |
242
+ | autoSave | It can be `true`, `false`, or an amount of milliseconds (integer). If `false`, you will have to perform `store.save()` manually. If `true`, the store will automatically perform `save()` when objects change. If an amount of milliseconds is provided, the objects are saved periodically AND when a change is detected. See [Editing objects](#editing-objects) for more information. | true |
209
243
  | saveDelay | An amount of milliseconds used to defer synching operations with the server. It triggers `store.save()` milliseconds after the last change on the store's objects is detedect. This allows to bundle together multiple changes operated by an interacting user. See [Editing objects](#editing-objects) for more information. | 1000 |
210
244
  | lazyLoad | A boolean. If set to `false`, the store is pre-populated with all the models' objects. If set to `true`, models' objects are loaded only on first usage (e.g., 'find', 'subscribe', 'getRelation'). LazyLoad operates per model, only the objects of the used models are loaded. | false |
211
245
 
@@ -216,7 +250,7 @@ The store can be configured with the following options:
216
250
  A model can be simply created with:
217
251
 
218
252
  ```js
219
- const book = new Model("book", `https://rest.example.net/api/v1/books`);
253
+ const book = new Model("book", `https://api.example.net/books`);
220
254
  ```
221
255
 
222
256
  However, sometimes you may want to define a more complex interaction with the API. In such cases you can pass options to perform more elaborated model's initializations.
@@ -227,16 +261,17 @@ const book = new Model("book", options);
227
261
 
228
262
  All the possible options for a model creation are (they are all optional):
229
263
 
230
- | Name | Description | Default |
231
- |----------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------|
232
- | retrieve | Describes the operation to retrieve the collection of objects from the REST API. It can be an operation object or a function. See [operations](#operations). | `{method: "get"}` |
233
- | insert | Describes the operation to insert a new object in the collection. It can be an operation object or a function. See [operations](#operations). | `{method: "post"}` |
234
- | update | Describes the operation to update objects of the collection. It can be an operation object or a function. See [operations](#operations). | `{method: "put"}` |
235
- | delete | Describes the operation to remove objects from the collection. It can be an operation object or a function. See [operations](#operations). | `{method: "delete"}` |
236
- | fields | An array of strings defining which attributes the retrieved objects should have. Essentially, it allows you to contemporarily specify the [X-Fields header](https://flask-restplus.readthedocs.io/en/stable/mask.html) and the [fields GET parameter](https://developers.google.com/slides/api/guides/performance#partial). This reduces transfer size and memory usage. E.g., if you have a collection of books, of which you are interested only in the name, you can define `fields: ["name"]`. In combination with `load` it allows for partial lazy load of the objects. | All the fields |
237
- | headers | A dictionary of headers for the HTTP request. E.g., `{"Authorization": "bearer XXXX"}`. | No headers |
238
- | load | A function that allows to enrich the objects on demand. E.g., you can use `fields` to download only the titles of a collection of books, and `load` to load completely the object. See [object enrichment](#object-enrichment). |
239
- | axios | It allows to specify an axios instance to be used for the queries. If not specified, a new one will be used. | A new axios instance |
264
+ | Name | Description | Default |
265
+ |-------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------|
266
+ | retrieve | Describes the operation to retrieve the collection of objects from the REST API. It can be an operation object or a function. See [operations](#operations). | `{method: "get"}` |
267
+ | insert | Describes the operation to insert a new object in the collection. It can be an operation object or a function. See [operations](#operations). | `{method: "post"}` |
268
+ | update | Describes the operation to update objects of the collection. It can be an operation object or a function. See [operations](#operations). | `{method: "put"}` |
269
+ | delete | Describes the operation to remove objects from the collection. It can be an operation object or a function. See [operations](#operations). | `{method: "delete"}` |
270
+ | fields | An array of strings defining which attributes the retrieved objects should have. Essentially, it allows you to contemporarily specify the [X-Fields header](https://flask-restplus.readthedocs.io/en/stable/mask.html) and the [fields GET parameter](https://developers.google.com/slides/api/guides/performance#partial). This reduces transfer size and memory usage. E.g., if you have a collection of books, of which you are interested only in the name, you can define `fields: ["name"]`. In combination with `load` it allows for partial lazy load of the objects. | All the fields |
271
+ | headers | A dictionary of headers for the HTTP request. E.g., `{"Authorization": "bearer XXXX"}`. | No headers |
272
+ | load | A function that allows to enrich the objects on demand. E.g., you can use `fields` to download only the titles of a collection of books, and `load` to load completely the object. See [object enrichment](#object-enrichment). |
273
+ | axios | It allows to specify an axios instance to be used for the queries. If not specified, a new one will be used. | A new axios instance |
274
+ | parseMoment | Automatically creates Moment.js objects out of ISO8601 strings. E.g., if an object has a property `createdAt: "2022-01-07T21:38:50.295Z"`, this will be transformed to a moment object. | |
240
275
 
241
276
 
242
277
  ### Operations
@@ -418,14 +453,29 @@ author1.getRelation("book", (book) => book.price < 20)
418
453
 
419
454
  The store has the following method.
420
455
 
421
- | Method | Description |
422
- |------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------|
423
- | addModel(model) | Introduce a new model to the store. If lazyLoad = false (default), the model is populated with the objects coming from the API. |
424
- | get(type, id) | It allows to retrieve an object based on its type and store's ID (see `getId()` in [objects methods](#objects-methods). The type is the name of the model. |
425
- | find(type,filterFunction) | The promise-oriented method to access objects given a type and a filter function. See [example 1](#example-1). |
426
- | delete(objects) | It deletes an array of objects. See [example 1](#example-3). |
427
- | delete(type, filterFunction) | It deleted objects given an array and a filter function. See [example 1](#example-3). |
428
- | insert(type, object) | It creates a new object of a given type and inserts it in the store. |
456
+ | Method | Description |
457
+ |--------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
458
+ | on(event, callback) | Method to subscribe to the events emitted by the store. See [events](#store-events) below. |
459
+ | addModel(model) | Introduce a new model to the store. If lazyLoad = false (default), the model is populated with the objects coming from the API. |
460
+ | get(type, id) | It allows to retrieve an object based on its type and store's ID (see `getId()` in [objects methods](#objects-methods). The type is the name of the model. |
461
+ | find(type, filterFunction) | The promise-oriented method to access objects given a type and a filter function. If the filter function is missing, all the objects are returned. See [example 1](#example-1). |
462
+ | delete(objects) | It deletes an array of objects. See [example 1](#example-3). |
463
+ | delete(type, filterFunction) | It deleted objects given an array and a filter function. See [example 1](#example-3). |
464
+ | insert(type, object) | It creates a new object of a given type and inserts it in the store. |
465
+ | subscribe(type, callback, filterFunction) | The callback-oriented method to access objects given a type and a filter function. It returns the key of the subscription, needed to unsubscribe. If the filter function is missing, all the objects are returned. **DataFlux remembers your query and calls the callback every time any change is affecting the result of your query.** See [example 5](#example-5---observability). |
466
+ | multipleSubscribe(subscriptions, callback) | A method to subscribe to multiple models. The first parameter is an array of models' names and filterFunctions, the second parameter is the callback to be called when the cumulative dataset is ready. E.g., `multipleSubscribe([["book", filterFunction1], ["author", filterFunction2]], callback)`. It returns the key of the subscription. See [example 5](#example-5---observability). |
467
+ | unsubscribe(key) | Method to terminate a subscription given a subscription key. See [example 5](#example-5---observability). |
468
+ | findOne(type, stateAttribute, context, filterFunction) | This method automatically injects and updates the React state with the requested data. If multiple objects satisfy the query, only the first is selected. The `stateAttribute` is the name of the attribute that will be added/updated in the state, the `context` is the React.Component. It automatically unsubscribe when the React.Component will unmount. See [example 6](#example-6---observability--react). |
469
+ | findAll(type, stateAttribute, context, filterFunction) | This method automatically injects and updates the React state with the requested data. The `stateAttribute` is the name of the attribute that will be added/updated in the state, the `context` is the React.Component. It automatically unsubscribe when the React.Component will unmount. If the filter function is missing, all the objects are returned. See [example 6](#example-6---observability--react). |
470
+
471
+ ## Store events
472
+ The store emits the following events:
473
+
474
+ | Name | Description |
475
+ |---------|---------------------------------------------------------------------------------------------------------------------------------------|
476
+ | error | To listen the errors emitted by the store. |
477
+ | save | Possible emitted values are `start` and `end`. They are emitted when the store starts/finishes to persist the data (API interaction). |
478
+ | loading | The event is emitted while a new model is loaded. The value contains something like `{status: "start", model: "book"}` |
429
479
 
430
480
  ## Objects methods
431
481
  Each object created is enriched with the following methods.
package/dist/Model.js CHANGED
@@ -33,12 +33,16 @@ function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _d
33
33
 
34
34
  function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
35
35
 
36
+ function _classPrivateMethodInitSpec(obj, privateSet) { _checkPrivateRedeclaration(obj, privateSet); privateSet.add(obj); }
37
+
36
38
  function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
37
39
 
38
40
  function _classPrivateFieldInitSpec(obj, privateMap, value) { _checkPrivateRedeclaration(obj, privateMap); privateMap.set(obj, value); }
39
41
 
40
42
  function _checkPrivateRedeclaration(obj, privateCollection) { if (privateCollection.has(obj)) { throw new TypeError("Cannot initialize the same private elements twice on an object"); } }
41
43
 
44
+ function _classPrivateMethodGet(receiver, privateSet, fn) { if (!privateSet.has(receiver)) { throw new TypeError("attempted to get private field on non-instance"); } return fn; }
45
+
42
46
  function _classPrivateFieldGet(receiver, privateMap) { var descriptor = _classExtractFieldDescriptor(receiver, privateMap, "get"); return _classApplyDescriptorGet(receiver, descriptor); }
43
47
 
44
48
  function _classApplyDescriptorGet(receiver, descriptor) { if (descriptor.get) { return descriptor.get.call(receiver); } return descriptor.value; }
@@ -49,6 +53,18 @@ function _classExtractFieldDescriptor(receiver, privateMap, action) { if (!priva
49
53
 
50
54
  function _classApplyDescriptorSet(receiver, descriptor, value) { if (descriptor.set) { descriptor.set.call(receiver, value); } else { if (!descriptor.writable) { throw new TypeError("attempted to set read only private field"); } descriptor.value = value; } }
51
55
 
56
+ var applyData = function applyData(obj, data) {
57
+ for (var att in data) {
58
+ if (att !== "id" || obj.id === undefined || att === "id" && obj.id === data.id) {
59
+ obj[att] = data[att];
60
+ } else {
61
+ return Promise.reject("The loading function cannot change the id of the object.");
62
+ }
63
+ }
64
+
65
+ return Promise.resolve(obj);
66
+ };
67
+
52
68
  var _type = /*#__PURE__*/new WeakMap();
53
69
 
54
70
  var _store = /*#__PURE__*/new WeakMap();
@@ -71,6 +87,8 @@ var _axios = /*#__PURE__*/new WeakMap();
71
87
 
72
88
  var _loadFunction = /*#__PURE__*/new WeakMap();
73
89
 
90
+ var _error = /*#__PURE__*/new WeakSet();
91
+
74
92
  var _addRelationByField = /*#__PURE__*/new WeakMap();
75
93
 
76
94
  var _addRelationByFilter = /*#__PURE__*/new WeakMap();
@@ -92,6 +110,8 @@ var Model = /*#__PURE__*/_createClass(function Model(name) {
92
110
 
93
111
  _classCallCheck(this, Model);
94
112
 
113
+ _classPrivateMethodInitSpec(this, _error);
114
+
95
115
  _classPrivateFieldInitSpec(this, _type, {
96
116
  writable: true,
97
117
  value: void 0
@@ -160,35 +180,31 @@ var Model = /*#__PURE__*/_createClass(function Model(name) {
160
180
  });
161
181
 
162
182
  _defineProperty(this, "load", function (obj) {
163
- return new Promise(function (resolve, reject) {
164
- var applyData = function applyData(data) {
165
- for (var att in data) {
166
- if (att !== "id" || obj.id === undefined || att === "id" && obj.id === data.id) {
167
- obj[att] = data[att];
168
- } else {
169
- return Promise.reject("The loading function cannot change the id of the object.");
170
- }
171
- }
172
- };
173
-
174
- if (_classPrivateFieldGet(_this, _loadFunction)) {
183
+ if (_classPrivateFieldGet(_this, _loadFunction)) {
184
+ return _this.getStore().whenSaved(_this.getType())["catch"](function () {
185
+ throw new Error("You cannot perform load() on an unsaved object.");
186
+ }).then(function () {
175
187
  var res = _classPrivateFieldGet(_this, _loadFunction).call(_this, obj.toJSON());
176
188
 
177
189
  if (typeof res === "string") {
178
- _classPrivateFieldGet(_this, _axios).call(_this, {
190
+ return _classPrivateFieldGet(_this, _axios).call(_this, {
179
191
  method: "get",
180
192
  url: res,
181
193
  responseType: "json"
182
194
  }).then(function (data) {
183
- return applyData(data.data);
184
- }).then(resolve);
195
+ return data.data;
196
+ });
185
197
  } else {
186
- res.then(applyData).then(resolve);
198
+ return res;
187
199
  }
188
- } else {
189
- reject("You must define a loading function in the model to enable load().");
190
- }
191
- });
200
+ }).then(function (data) {
201
+ return applyData(obj, data);
202
+ })["catch"](function (error) {
203
+ return _classPrivateMethodGet(_this, _error, _error2).call(_this, error);
204
+ });
205
+ } else {
206
+ return _classPrivateMethodGet(_this, _error, _error2).call(_this, "You must define a loading function in the model to enable load().");
207
+ }
192
208
  });
193
209
 
194
210
  _defineProperty(this, "addRelation", function (model, param2, param3) {
@@ -216,17 +232,15 @@ var Model = /*#__PURE__*/_createClass(function Model(name) {
216
232
  var filterRelation = _classPrivateFieldGet(_this, _includes)[includedType];
217
233
 
218
234
  if (filterRelation) {
219
- return _this.getStore().find(includedType, function (item) {
220
- return filterRelation(parentObject, item);
221
- }).then(function (data) {
222
- if (filterFunction) {
223
- return data.filter(filterFunction);
224
- }
225
-
226
- return data;
235
+ return parentObject.load()["catch"](function () {}).then(function () {
236
+ return _this.getStore().find(includedType, function (item) {
237
+ return filterRelation(parentObject, item);
238
+ }).then(function (data) {
239
+ return filterFunction ? data.filter(filterFunction) : data;
240
+ });
227
241
  });
228
242
  } else {
229
- return Promise.reject("The relation doesn't exist");
243
+ return _classPrivateMethodGet(_this, _error, _error2).call(_this, "The relation doesn't exist");
230
244
  }
231
245
  });
232
246
 
@@ -235,7 +249,15 @@ var Model = /*#__PURE__*/_createClass(function Model(name) {
235
249
  });
236
250
 
237
251
  _defineProperty(this, "retrieveAll", function () {
238
- return (0, _modelHooksUtils.executeHook)("retrieve", _classPrivateFieldGet(_this, _retrieveHook), null, _classPrivateFieldGet(_this, _axios)).then(_classPrivateFieldGet(_this, _toArray));
252
+ return (0, _modelHooksUtils.executeHook)("retrieve", _classPrivateFieldGet(_this, _retrieveHook), null, _classPrivateFieldGet(_this, _axios)).then(function (data) {
253
+ if (Array.isArray(data)) {
254
+ return data;
255
+ } else {
256
+ _classPrivateFieldSet(_this, _singleItemQuery, true);
257
+
258
+ return [data];
259
+ }
260
+ });
239
261
  });
240
262
 
241
263
  _defineProperty(this, "insertObjects", function (objects) {
@@ -275,9 +297,13 @@ var Model = /*#__PURE__*/_createClass(function Model(name) {
275
297
  writable: true,
276
298
  value: function value(objects, action) {
277
299
  if (_classPrivateFieldGet(_this, _singleItemQuery)) {
278
- return (0, _batchPromises["default"])(_classPrivateFieldGet(_this, _batchSize), objects, action);
300
+ return (0, _batchPromises["default"])(_classPrivateFieldGet(_this, _batchSize), objects.map(function (i) {
301
+ return i.toJSON();
302
+ }), action);
279
303
  } else {
280
- return action(objects);
304
+ return action(objects.map(function (i) {
305
+ return i.toJSON();
306
+ }));
281
307
  }
282
308
  }
283
309
  });
@@ -288,8 +314,6 @@ var Model = /*#__PURE__*/_createClass(function Model(name) {
288
314
  if (Array.isArray(data)) {
289
315
  return data;
290
316
  } else {
291
- _classPrivateFieldSet(_this, _singleItemQuery, true);
292
-
293
317
  return [data];
294
318
  }
295
319
  }
@@ -318,6 +342,10 @@ var Model = /*#__PURE__*/_createClass(function Model(name) {
318
342
 
319
343
  _classPrivateFieldSet(this, _type, name);
320
344
 
345
+ this.options = {
346
+ parseMoment: options.parseMoment
347
+ };
348
+
321
349
  _classPrivateFieldSet(this, _store, null);
322
350
 
323
351
  _classPrivateFieldSet(this, _includes, {});
@@ -356,4 +384,10 @@ var Model = /*#__PURE__*/_createClass(function Model(name) {
356
384
 
357
385
  });
358
386
 
359
- exports["default"] = Model;
387
+ exports["default"] = Model;
388
+
389
+ function _error2(error) {
390
+ error = error.message || error;
391
+ this.getStore().pubSub.publish("error", error);
392
+ return Promise.reject(error);
393
+ }
@@ -9,6 +9,8 @@ var _fingerprint = _interopRequireDefault(require("./fingerprint"));
9
9
 
10
10
  var _uuid = require("uuid");
11
11
 
12
+ var _moment = _interopRequireDefault(require("moment/moment"));
13
+
12
14
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
13
15
 
14
16
  function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
@@ -33,9 +35,11 @@ function _classExtractFieldDescriptor(receiver, privateMap, action) { if (!priva
33
35
 
34
36
  function _classApplyDescriptorGet(receiver, descriptor) { if (descriptor.get) { return descriptor.get.call(receiver); } return descriptor.value; }
35
37
 
38
+ var dateRegex = new RegExp("^[0-9][0-9][0-9][0-9]-[0-9].*T[0-9].*Z$");
39
+
36
40
  var _loaded = /*#__PURE__*/new WeakMap();
37
41
 
38
- var Obj = /*#__PURE__*/_createClass(function Obj(values, model) {
42
+ var Obj = /*#__PURE__*/_createClass(function Obj(values, _model) {
39
43
  var _this = this;
40
44
 
41
45
  _classCallCheck(this, Obj);
@@ -49,11 +53,15 @@ var Obj = /*#__PURE__*/_createClass(function Obj(values, model) {
49
53
  if (_classPrivateFieldGet(_this, _loaded)) {
50
54
  return Promise.resolve(_this);
51
55
  } else {
52
- return _this.getModel().load(_this).then(function () {
56
+ var model = _this.getModel();
57
+
58
+ return model.load(_this).then(function () {
53
59
  _classPrivateFieldSet(_this, _loaded, true);
54
60
 
61
+ return model.getStore().update([_this], true); // Propagate update
62
+ }).then(function () {
55
63
  return _this;
56
- });
64
+ }); // return always this
57
65
  }
58
66
  });
59
67
 
@@ -75,8 +83,7 @@ var Obj = /*#__PURE__*/_createClass(function Obj(values, model) {
75
83
  }
76
84
 
77
85
  _this[attribute] = value;
78
-
79
- _this.getModel().getStore().update([_this]);
86
+ return _this.getModel().getStore().update([_this]);
80
87
  });
81
88
 
82
89
  _defineProperty(this, "save", function () {
@@ -94,7 +101,11 @@ var Obj = /*#__PURE__*/_createClass(function Obj(values, model) {
94
101
  for (var _i = 0, _attrs = attrs; _i < _attrs.length; _i++) {
95
102
  var a = _attrs[_i];
96
103
 
97
- if (typeof _this[a] !== "function") {
104
+ if (_this[a] instanceof _moment["default"]) {
105
+ out[a] = _this[a].toISOString();
106
+ } else if (_this[a] instanceof Date) {
107
+ out[a] = (0, _moment["default"])(_this[a]).toISOString();
108
+ } else if (typeof _this[a] !== "function") {
98
109
  out[a] = _this[a];
99
110
  }
100
111
  }
@@ -107,12 +118,20 @@ var Obj = /*#__PURE__*/_createClass(function Obj(values, model) {
107
118
  });
108
119
 
109
120
  this.getModel = function () {
110
- return model;
121
+ return _model;
111
122
  };
112
123
 
113
- Object.keys(values).forEach(function (key) {
114
- _this[key] = values[key];
115
- });
124
+ var frEach = _model.options.parseMoment ? function (key) {
125
+ if (dateRegex.test(values[key])) {
126
+ var mmnt = (0, _moment["default"])(values[key]);
127
+ _this[key] = mmnt.isValid() ? mmnt : values[key];
128
+ } else {
129
+ _this[key] = values[key];
130
+ }
131
+ } : function (key) {
132
+ return _this[key] = values[key];
133
+ };
134
+ Object.keys(values).forEach(frEach);
116
135
  var id;
117
136
 
118
137
  if (this.id && (typeof this.id === "string" || typeof this.id === "number")) {