Closed Qsppl closed 9 months ago
For the sake of future readers, I assume that you have the following relation:
user -> comment[]
(one to many)
Regardless of how the relation is stored in the database, it's always the safest to store reverse relation in the model, then you have many to one (from many).
In this case, you would have:
const Comment = {
user: User,
[store.connect]: {
...,
list({ user }) {
// get list of comments for the user
return api.get(`/users/${user}/comments`)...
},
},
};
In the above example, the user model doesn't have to include that relation at all. If you need a list of comments related to the user you call const listForUser = store.get([Comment], { user: "1" })
.
To prevent invalidating all of the lists (for all of the users), when creating a comment, you can clear the list for a specific user by passing the list to the store.clear(listForUser, false)
.
EDIT: This nested model idea was wrong, sorry (I removed it to avoid confusion) ;)
Thanks, store.clear(model, false) completely solved the problem.
I store pointers to related models and in both sides:
It is necessary to store pointers to comments with the user (1) in order to have information about user comments before loading the comments themselves. This is especially important when lazy loading comments.
Here we see that the user/company has comments:
But here it’s not:
In this case, comments will not load until the user opens the corresponding comments section
With this approach, hybrids loads each model separately, but in my case this is even better due to the use of http2 and http caching. In this option, when changing one comment, there is no need to invalidate all user comments, and there is also no need to write complex logic for updating the cache when adding a new comment.
Example: https://codepen.io/qsppl/pen/gOqqzPX?editors=1011
There is a User and Comments about him. When creating a new Comment, you need to update the User model to add this Comment to him.
Below I have described 4 options to solve this problem, but they all have problems. Maybe there is a way to simply reload the model from the server as is done the first time the model is requested, but do not delete the cache until new data is loaded?