angular2-jsonapi icon indicating copy to clipboard operation
angular2-jsonapi copied to clipboard

Refactoring: Use plain old javascript objects as data models

Open reva2 opened this issue 8 years ago • 5 comments

In current implementation data models highly coupled with data storage. I think it will be better if we will use POJO augmented with decorators for data models. I.e. all methods that change data in underlying storage (currently, save()) should be moved from JsonApiModel to JsonApiDataStore.

Typical interaction with data storage can look like:

// create record
let author = new AuthorModel();
storage.saveRecord(author);

// updating record
storage.findRecord(BookModel, '1').subscribe(
  (book) => {
    book.title = "New title";
    storage.saveRecord(book);
  }
);

// deleting record
storage.findRecord(BookModel, '1').subscribe(
  (book) => storage.deleteRecord(book);
);

This approach have following advantages:

  • data models can be plain old javascript objects without dependency on JsonApiDataStorage. It can be easily created and tested.
  • in the future we can easily support multiple operations in the single request (json-api/json-api#795). Something like:
storage.beginTransaction();

/* posts: BlogPostModel[] */
posts.forEach((post) => {
  post.published = true;
  storage.saveRecord(post);  // request will be delayed because of transaction
});

storage.commit(); // update all posts in underlying storage using single request

reva2 avatar Oct 12 '16 17:10 reva2

I also think it's a good idea to move the logic to the JsonApiDataStore. Removing the now needed inheritance of JsonApiModel of the data models will make it much easier to deal with the models in forms and components.

HennerM avatar Oct 17 '16 11:10 HennerM

Any idea on when this modification could be released ? :) Like said in #49, I can't use any application state container like ng2-redux, because I can't store my models as they contain some properties injected by JsonApiModel and some circular references that cannot be passed into JSON.stringify

Tinostarn avatar Nov 04 '16 09:11 Tinostarn

I think this is a great idea, right now its very tricky to properly test components and services as bringing in the models is not so trivial and very couple with the librarie's data storage like mentioned, Would love to know if there are some plans on moving to something like this. I know that might mean some breaking changes, but maybe thats ok at this stage.

joaogarin avatar Jul 06 '17 08:07 joaogarin

Something new about this issue?

ZeevKatz avatar Jul 03 '18 12:07 ZeevKatz

This would be great. Quite a lot of extra working writing unit tests I've discovered, and also, Tinostarn's comment on ng2-redux.

Any plans to implement?

xaun avatar May 29 '19 08:05 xaun