Ember Data: working with API that returns larger payload on details endpoint than list endpoint

StackOverflow https://stackoverflow.com//questions/24017236

  •  21-12-2019
  •  | 
  •  

Question

I'm using Ember with Ember Data and working with a REST API that returns only a small set of properties at the list endpoint and the full payload at the details endpoint. For example:

URL: /api/users

{
    "users":[
        {"id":1,"name":"Bob"},
        {"id":2,"name":"Sam"}
    ]
}

URL: /api/users/1

{
    "user":{
        "id":1,
        "name": "Bob",
        "description": "Lorem ipsum dolor"
    }
}

Notice how /api/users/1 returns more properties than the list. With Ember Data, how do you get it to fetch the full payload when necessary if I have my Routes set up as follows?

App.UsersRoute = Ember.Route.extend({
    model: function () {
        return this.store.find('user');
    }
});

App.UserRoute = Ember.Route.extend({
    model: function (params) {
        return this.store.find('user', params.user_id);
    }
});

The problem is this line:

this.store.find('user', params.user_id)

It doensn't request the full payload from the server if the list has already be loaded, so calling the store's find method returns the user with limited properties from its cache.

Was it helpful?

Solution

You could do something like:

  var user = this.store.getById('user', params.user_id);
  if (user) {
    return user.reload();
  } else {
    return this.store.find('user', params.user_id);
  }

Check store methods (getById, hasRecordForId, recordIsLoaded) and model reload.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top