Willem de Wit
Willem de Wit

Reputation: 8732

Ember data bulk fetch async hasMany relationship records

I'd like to know whether it is possible to configure Ember data in a way that async hasMany relationships are loaded in a single request.

Given the following model:

// models/post.js
export default DS.Model.extend({
  comments: DS.hasMany()
});

// models/comments.js
export default DS.Model.extend({
  ...
});

When I reference the property comments somewhere in the template or controller, it will fetch the related comments of the post one-by-one in separate requests. This results in many requests and I'd like to combine those into a single request with a filter on id-property.

Upvotes: 3

Views: 598

Answers (2)

Jeff
Jeff

Reputation: 6953

There is a switch you have to enable for the desired behaviour called coalesceFindRequests: true that you can set in you application adapter like so:

// adapters/application.js
import DS from 'ember-data';

export default DS.RESTAdapter.extend({
    coalesceFindRequests: true,
});

Now Ember will fetch multiple records of known id via ..api/comments?ids[]=1&ids[]=2

I suppose it'll be the same for a JSONAdapter.

Upvotes: 3

Lux
Lux

Reputation: 18240

Yes, you should use link relationships:

Instead of this:

relationships: {
    commend: {
        data: [
            { id: '1', type: 'comment' },
            { id: '2', type: 'comment' }
        ]
    }
}

do this:

relationships: {
    comments: {
        links: {
            related: 'http://example.com/post/A/comments'
        }
    }
}

The nice thing about this is that you can 100% adjust this in your backend.

Upvotes: 0

Related Questions