1

I have an API that doesn't return JSON data in a format that Ember-Data expects. Especially when getting a list of resources versus a single resource.

For example, GET /api/widgets/{id}

Should return a single widget model that might look like this:

//app/models/widget.js

import DS from 'ember-data';

export default DS.Model.extend({
   name: DS.attr('string'),
   weight: DS.attr('number'),
   color: DS.attr('string')
});

Whereas getting the full list of widgets via GET /api/widgets/ returns a model that should look like this:

// app/models/widgetlist.js

import DS from 'ember-data';

 export default DS.Model.extend({
   total: 22,
   widgets: DS.hasMany('widget')
});

(I think that's how my widget list model should look. It's essentially a total count of widgets in system and current paginated set of widgets)

I'm having a really hard time figuring out what combination of models, custom adapter and/or custom serializer I need in order to get this to work.

EDIT:

// Server responses examples

// GET api/widgets/77

{  
  "id":77,
  "name":"Acoustic Twangdoodle",
  "weight":3,
  "color":"purple"
}

// GET api/widgets/

{
  "total":22,
  "widgets":[
  {
     "id":77,
     "name":"Acoustic Twangdoodle",
     "weight":3,
     "color":"purple"
  },
  {
     "id":88,
     "name":"Electric Twangdoodle",
     "weight":12,
     "color":"salmon"
  }
  ]
}
PercivalMcGullicuddy
  • 5,263
  • 9
  • 46
  • 65
  • *API that doesn't return JSON data in a format that Ember-Data expects* this is exactly why I don't use ember data. It's too inflexible. Just make a ajax call using your ajax call method of choice and don't use ember data at all – Liam Jan 07 '19 at 16:43
  • @liam I'm just about ready to give up. I wonder if Mirage will all still work without ember data. I rely on it heavily because I'm way ahead of the server side team :) – PercivalMcGullicuddy Jan 07 '19 at 16:45
  • I don't use mirage I'm afraid so I don't know. Someone will prob have an ember data solution. – Liam Jan 07 '19 at 16:51
  • @PercivalMcGullicuddy You can definitely use Mirage without Ember Data - you can even use models & serializers to reduce duplication. But I would start by writing out the route handlers by hand. – Sam Selikoff Jan 07 '19 at 17:16
  • 1
    @SamSelikoff Thanks. I just implemented simple ajax calls using ember-ajax (as suggested by @Liam) and everything works as it should/expected. Even Mirage. – PercivalMcGullicuddy Jan 07 '19 at 17:19

1 Answers1

2

Thats only one model!

Now I don't see how your pagination works. Depending on that maybe you should not use findAll but instead use query to load a paginated set.

The total is not part of the model but of the metadata. Use a custom JSONSerializer and let extractMeta return this.

Depending how your pagination works you wanna do something like store.query('widget', { page: 3 }). If you speak more about how to access page 2 or so it will be easier to explain this.

Lux
  • 17,835
  • 5
  • 43
  • 73