Very simple Ember Data structure from JSON API


#1

Good God!

I just want to set MODEL data from JSON API with Ember Data.

Let’s take some base example (list of user names):

URL: https://jsonplaceholder.typicode.com/users

My app/models/user file:

export default DS.Model.extend({
    name: DS.attr()
});

My app/adapters/application.js file:

export default DS.JSONAPIAdapter.extend({
  host: 'https://jsonplaceholder.typicode.com'
});

My app/router/users.js file:

export default Ember.Route.extend({
  model (){
    return this.store.findAll('user');
  }
});

My app/templates/users.hbs file:

{{#each model as |user|}}
  <li>{{user.name}}</li>
{{/each}}

What should I set to get a list of user names in MODEL and my template?


#2

I just looked at this but as we almost always use ember-pouch and not JSONAPIAdapter I don’t know how to fix the error.

Assertion Failed: normalizeResponse must return a valid JSON API document: * One or more of the following keys must be present: “data”, “errors”, “meta”.

See Twiddle:

https://ember-twiddle.com/8bbf99d224037e3913e712c1c0752796?openFiles=adapters.application.js%2C&route=%2Fusers


#3

Thanks for your answer Broerse!

So the reason why the data can not be retrieved by JSONAPIAdapter is the missing data key in the JSON file?

I have to check and understand how the ember-pouch works.


#4

I have created a jsonapi mock that works for 24 hours. Insert it in the Twiddle and it works https://demo5604487.mockable.io/

Content-Type application/vnd.api+json

{
  "data": [{
    "type": "users",
    "id": "1",
    "attributes": {
      "name": "John"
    }
  },{
    "type": "users",
    "id": "2",
    "attributes": {
      "name": "James"
    }      
  }]
}

(My pouch example https://github.com/broerse/ember-cli-blog)


#5

Updated my twiddle so this works for 24 hours.

https://ember-twiddle.com/8bbf99d224037e3913e712c1c0752796?route=%2Fusers


#6

Thank you for your help! :slight_smile:


#7

The API you are trying to call does not follow the jsonapi.org specification.

In order to use ember-data out of the box, you need to use an api that follows the jsonapi specification.

Here are some examples.

http://jsonapi.org/implementations/#examples


#8

You can also just start out with the RESTAdapter/RESTSerializer and adapt from there. For example, you could overwrite the handleResponse method to change the format the API returns into a format the default adapters can work with.