Im using Ember 3.2 with JSON API end points. Im stuck on how to map data the server provides me to my models.
I have the following models:
// Model Zoo
export default DS.Model.extend({
animals: hasMany('animal', {polymorphic: true})
})
// generic animal model
export default DS.Model.extend({
})
// animal-mamal model
export default DS.Model.extend({
...
})
// animal-reptile model
export default DS.Model.extend({
...
})
When consuming the resource example.com/zoo/:id/animal
Im getting the following response:
{
"data" : [ {
"id" : ":some-id",
"type" : "mamal-animals",
"attributes" : {
...
},
"relationships" : {
...
},
"links" : {
...
}
}, {
"id" : ":some-id",
"type" : "reptile-animals",
"attributes" : {
...
},
"relationships" : {
...
},
"links" : {
...
}
}]
}
Without implementing anything in the serializer I get the following in the console:
Encountered a resource object with type
"mamal-animals", but no model was found for
model name "mamal-animals" (resolved model name
using '(unknown mixin).modelNameFromPayloadKey("mamal-animals")').
My models do not map with the type the server gives me. After getting that message, I wrote some code in the method modelNameFromPayloadKey from the Application serializer.
It basically maps the types the server provides me with to the models I have in the frontend.
// Map Backend type to Frontend models
const PAYLOAD_KEY_TO_MODEL = {
'mamal-animals': 'animal-mamal',
'reptile-animals': 'animal-reptile'
}
export default DS.JSONAPISerializer.extend({
// Map payload keys return by API to corresponding models in our app
modelNameFromPayloadKey(key) {
if(PAYLOAD_KEY_TO_MODEL[key]){
return this._super(PAYLOAD_KEY_TO_MODEL[key]);
} else {
return this._super(...arguments);
}
}
})
Now it crashes with the following error:
Assertion Failed: You tried to push data with a
type 'mamal-animals' but no model could be found with that name.
It seems it is still trying to find the type returned by the server instead of the model I provided.
I thought that the model name would be taken by implementing the modelNameFromPayloadKey method.
Any solution or ways to debug issues with serializer?
Aucun commentaire:
Enregistrer un commentaire