lundi 19 septembre 2016

Emberjs Catch-22 - parent computed properties that count hasMany related objects

Let's start with a common scenario where you have a computed property on a model:

models/coney.js

bunniesTotal: Ember.computed.alias('babyBunnies.length')

Lets say the entry point to the application is an index page showing all the parents Coneys:

routes/coneys/index

The API returns all the Coneys but it's paged, so only 50 appear per page (great, we don't want too many rabbits running around do we?)

Along with each Coney (parent rabbit) comes all of its children (since there are only a few of 'em, and they's only littl'uns - ie. small payload!)

So the bunniesTotal will always be accurate, and you can see it on each Coney in the list on the coneys/index page. Great, wonderful, a common example you see everywhere in Ember tutorials. Ember goodness.

Even more Ember goodness - after a user visits /coneys/new.js and adds a new Coney and some BabyBunnies, the user will see the above bunniesTotal update automatically when they come back to /coneyes/index, since the new record BabyBunny is in the Ember Store Warren. Watership Down, come on!

Now let's travel to the future and scale our data warren. Uh oh.

Now the Coneys have thousands of children and maybe thousands of grandchildren too (yeah, Rabbits, go figure!)

It doesn't make sense now, on the coneys/index page, to load ALL the children BabyBunnies for all 50 parent Coneys on that first hit. Not good.

So let's modify the API, and remove the children BabyBunnies, so that each parent Coney must individually request them (eg. when you go to coneys/edit for example).

(Ok, enough with the strikethroughs already!)

But...what do you do about the count? Now the client doesn't know how many children each parent might have.

You could include a property on each parent in the API instead of in Ember. So now you count the children on the server and send that total to Ember. Maybe a meta.children_total or just a property on the model. Ok, cool.

But now when a user adds a child on the client, the total is not updated automatically. You've lost that Ember goodness. and your index page has now 'degraded' in the eyes of the user.

The user, after adding a new 'child' and getting redirected to coneys/index, will not see the total update. They will think something is wrong. What happened to the new baby rabbit child I just created?

So, after that little time-travelling essay, here is the question.

Is there some Ember way to solve this Catch-22?

Maybe a background refresh of the parent after adding a child to it. Or a way to just request the meta data for the parent, or some other Ember magic?

I had a look at ds-references, but didn't seem to answer it.




Aucun commentaire:

Enregistrer un commentaire