Side loading data with JsonAPI links

I’ve been having a difficult time with this over the last two days with side loading data via the links attribute in a JsonAPI payload. Essentially I have a hasMany relationship where I attempt to lazy load the data. I have a nested API structure and want the call to look like this /posts/1/comments. I have this working using the RESTAdapter but it doesn’t work with the JSONAPIAdapter.

Post Model

export default DS.Model.extend({
  name: DS.attr('string'),
  comments: DS.hasMany('comment', {async:true})
});

Comment Model

export default DS.Model.extend({
  name: DS.attr('string'),
  post: DS.belongsTo('post')
});

JSON payload

  "data": [{
    "type": "posts",
    "id": "1",
    "attributes": {
      "id": 1
      "name": "my title"
    },
    "links": {
      "comments": "comments"
    }
  }]

Template

<ul>
  {{#each model as |post|}}
    {{#each post.comments as |comment|}}
      <li>{{comment.name}}</li>
    {{/each}}
  {{/each}}
</ul>

I have read many different posts and blogs about how Ember’s REST adapter uses links to load related data, and I do have this working with a REST adapter, although with a different payload to match the REST adapter’s expectations. I have tried many different combinations of payloads but nothing so far has worked.

Hi @patryk,

Your payload should look like:

"data": [{
  "type": "posts",
  "id": "1",
  "attributes": {
    "id": 1
    "name": "my title"
  },
  relationships: {
    comments: {
      links: {
        related: "/posts/1/comments"
      }
    }
  }
}]

If you need some more guidance on how to generate links, there is something similar with the Github API in this article: Fit Any Backend Into Ember with Custom Adapters & Serializers - Ember Igniter (search for payload.repos_url)

Awesome, this worked for me. Thank you.

1 Like