I'm using ember & ember-data to try and consume a json feed from the server. Here is my code:
App = Ember.Application.create();
DS.RESTAdapter.configure(
"plurals", {
category: 'categories'
}
);
App.Store = DS.Store.extend({
revision: 12,
adapter: DS.RESTAdapter.create({
url: 'app'
})
});
App.Router.map(function(){
this.resource('categories');
});
App.CategoriesRoute = Ember.Route.extend({
model: function() {
return App.Category.find();
}
});
var attr = DS.attr;
App.Category = DS.Model.extend({
name: attr('string')
});
Now this works fine with a testing server. Using the following JSON
{
"categories":[
{
"name":"Beef",
"id":1
},
{
"name":"Pork",
"id":2
}
]
}
However in production the server provide the following json:
{
"success":true,
"message":"Request successful",
"total":2,
"data":[
{
"name":"Beef",
"id":1
},
{
"name":"Pork",
"id":2
}
]
}
I can't for the life of me work out how to use the serializer to consume the live json. Any help would be appreciated. Thanks in advance.
UPDATE:
I've since tried to write the serializer but it doesn't appear to be working...
see below
App.Store = DS.Store.extend({
revision: 12,
adapter: DS.RESTAdapter.create({
url: 'app',
serializer: DS.RESTSerializer.extend({
extract: function(loader, json, type, record) {
var root = 'data';
this.sideload(loader, type, json, root);
this.extractMeta(loader, type, json);
if (json[root]) {
if (record) { loader.updateId(record, json[root]); }
this.extractRecordRepresentation(loader, type, json[root]);
}
}
})
})
});
Which now produces this error Uncaught Error: assertion failed: Your server returned a hash with the key data but you have no mapping for it
You have 2 options
UPDATE: write your own serializer UPDATE 2: get rid of unused functions
https://github.com/emberjs/data/blob/master/packages/ember-data/lib/serializers/json_serializer.js#L196
You can inherit from the DS.RESTSerializer and change extract with this code
extract: function(loader, json, type, record) {
var root = 'data';
if (json[root]) {
if (record) { loader.updateId(record, json[root]); }
this.extractRecordRepresentation(loader, type, json[root]);
}
}
This assumes that the content of request will always be under the data key of your json.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With