vendredi 1 décembre 2017

ember-data: modeling a user-maintained list of products

Trying to wrap my head around how to efficiently model and code a "saved items" list for logged-in users.

I want the user to be able to click "save item" from a product page, and it will add the item to a list kept in their user profile that has its own route that displays their items and allows them to manage the list. On that route, anytime there are changes to the list (like, item is removed), it should refresh to reflect the changes.

I'd think the user model would look something like this:

import DS from 'ember-data';
const { attr, belongsTo, hasMany } = DS;

export default DS.Model.extend({
    savedItems: hasMany('product'),
    ...
});

And then I can add items to it with this action:

actions: {
    addSavedItem(product) {
        this.get('store').findRecord('user', 'me').then(user => {
            user.get('savedItems').pushObject(product);
            user.save();
        });
    },
}

And load those saved items in my saved-items route like:

model() {
    return this.get("store").findRecord('user', 'me').then(user => {
        return user.get('savedItems');
    });
}

That works! BUT...product passes in the entire product object. Name, prices, description, etc. Then save sends it all in the payload to the back end. Then the back-end has to send it all back (I think) for this to stay working.

Is there a way to have savedItems store just product IDs, and have ember-data load the rest of the product data as-needed? Product ID is all I need to persist to the back end.

I've tried removing the relationship and having savedItems be an array:

savedItems: attr('')

that stores just product IDs. And I had partial success there. But I can't figure out how to set up the model hook in the saved-items route so the it refreshes whenever there are changes to that list.

Any help appreciated!




Aucun commentaire:

Enregistrer un commentaire