Partial load of an async model


#1

I have 2 models, a post model and a comment model. I would like to download the comments asynchronously, and it works fine with the following models.

//models/post.js
export default DS.Model.extend({
	date: attr('string'),
	user: belongsTo('user'),
	comments: hasMany('comment', {async: true})
});

//models/comment.js
export default DS.Model.extend({
	date: attr('string'),
	user: belongsTo('user'),
	value: attr('string')
});

Although sometimes, a post can have hundreds of comment ids returned, and I don’t want to load all the comments in one shot, this can be too big, so I’d like to limit the request to the ids that I want first.

If I am doing the following, it will download all the comments at once.

this.store.findRecord('post', 1).then((post) => {
	post.get('comments'); //Will call the server to load all the comments
});

I was thinking to get the list of ids I got, slice the array to get the first 10 comments and send the request that way, but I’m not even able to access the ids, as when I call .get('comments') it loads them all.

I’m wondering what could be my best solution to avoid to load all the comments in one shot?

Thanks


#2

Hey tilix, have you tried using the ember-data-partial-model add-on?

For the first 10, you could query the store and return that promise.


#3

I’m dealing with this problem too. One idea I had if you’re using Ember Data 2.5 or higher is to call post.hasMany('comments').ids(), which returns the list of ids without a server request, and then splice that list and make a custom request for only those models.

The problem with this approach is that you don’t know which records you’re getting. There’s no way to sort them before you retrieve them because you’re only dealing with ids.