I'm learning Ember (2.14) and currently working with Ember.Data. I need to fetch data from an API that returns an entity relations by its url on the server. Like so :
{
"id": 12,
"name" : "John",
"friends": [
"https://api/people/24",
"https://api/people/55",
"https://api/people/34",
]
}
I'm using the JSONSerializer, with normalize to parse fields of hasMany relations into a single id for Ember.Data to handle, like so
export default JSONSerializer.extend({
normalize(typeClass, hash) {
let fields = Ember.get(typeClass, 'fields');
fields.forEach(function(field,index) {
if(field === 'hasMany'){
// extract id from every relation containing url with ids
hash[index] = hash[index].map((value)=>{
if(value.indexOf('my_api_domain') > -1){
const id = value.substring(value.lastIndexOf('/')+1,value.length);
return id.length > 0 ? id : value;
}
return value;
});
}
});
return this._super.apply(this, arguments);
}
});
I don't know much of Ember yet, but it feels very messy, is there a cleaner way to do it ?
Aucun commentaire:
Enregistrer un commentaire