Search code examples
ember.jsember-datajson-api

How to get included values of jsonapi on a router with ember-data?


I'm using jsonapi directives to make a connection between ember.js app and an API. I have a track that could have like 50 or more comments and I need to load them on a route to perform some logic.

This is and example response of the API:

{
   "data": {
       "id": 1,
       "type": "track",
       "attributes": {
           "name": "XPTO"
       },
       "relationships": {
           "comment": {
               "data": [
                   {"id": 1, "type": "comment"}
               ]
           }
       }
   },
   "include": [
       {
          "id": 1,
          "type": "comment",
          "attributes": {
             "text": "Lorem ipsum..."
          }
       }
   ]
}

Now imagine it with 50 comments, this would be very consuming to make a request for each call. If I do it in a view with an each loop, it doesn't make all the requests, but it I try to access it in a Route, it will make all the requests. How do I achieve that with the following code?

this.store.findRecord('track', 1).then((t) => {
   // logic here
   // I tried this but it would make all the requests too
   t.get('comments');
})

Solution

  • U can use property "coalesceFindRequests" in your adapter

    coalesceFindRequests: true
    

    If you set coalesceFindRequests to true it will instead trigger the following request:

    GET /comments?ids[]=1&ids[]=2
    

    so this makes only one call for all the comments.

    Note: Requests coalescing rely on URL building strategy. So if you override buildURL in your app groupRecordsForFindMany more likely should be overridden as well in order for coalescing to work.