Zorig Zorig - 2 months ago 32
JSON Question

Ember serializer customization for alternate url

I am a newbie to ember. So here is what i faced. I got backend RESTAPI written in python/Django. It provides following json response on

/api/works/


[
{
"id": 17,
"title": "about us",
"description": "some project",
"owner": "admin"
},
{
"id": 19,
"title": "test1 profit project",
"description": "dev null",
"owner": "test1"
}
]


also on detail view E.g:
/api/works/17/
:

{
"id": 17,
"title": "about us",
"description": "some project",
"owner": "admin"
}


there is also
/api/works/17/tasks/
for listing work tasks

[
{
"id": 2,
"title": "secondWorkTask",
"description": "task2 description",
"due_date": "2016-09-26",
"assign": 1,
"project": "about us"
},
{
"id": 3,
"title": "some task name",
"description": "some task description",
"due_date": "2016-08-27",
"assign": 2,
"project": "about us"
}
]


on the front-end side i am using ember-cli version2.7.0 + ember-django-adapter. I can get /api/works without problem.

serializer on ember to get project:

export default DRFSerializer.extend({
normalizeFindAllResponse(store, primaryModelClass, payload, id, requestType) {
payload.data = payload;
return this._super(...arguments);
}
});


What i want to achieve is on the ember side when work detail url on the ember side(
emberexample-app.com/app/17/
) load, it must show all tasks. Currently i can get work detail by this url
/api/works/17/
with above serializer. But how can i get tasks? Please help me to find a way to solve this.

Answer

The serializer are used to customize the loading and saving (or serialization and deserialization) of data.

To customize the URLs you must use an Adapter,(e.g. RESTAdapter is my most used adapter).

That will work in the case you want to create (urlForCreateRecord) or update (urlForUpdateRecord) tasks but it may not directly work if you just want to convert a work.get('tasks') following a belongsTo relationship to a GET http://endpoint/work/<work_id>/tasks, at least in my case it didn't "just work"ed.

A solution I found that works very well is adding a property links as a plain object to the parent objects that contains links to the different child models you want to retrieve as properties.

Something like this:

/* app/adapters/work.js */
import DS from 'ember';

export default DS.RESTSerializer({
    normalize (model, hash, prop) {
        hash.links = hash.links || {};
        hash.links.tasks = this.buildURL(model, hash.id) + '/tasks';
        return this._super(model, hash, prop);
    }
});

In this example, when Ember try to get a tasks property from a work model, it will make a GET to the URL that work.links.tasks contains.

Comments