sylwia
sylwia

Reputation: 381

Ember.js REST adapter handling different JSON structure

I'm using REST adapter, when I call App.Message.find() Ember.js makes call to the /messages to retrieve all messages and expect to see JSON structure like this:

{
    "messages": [] // array contains objects
}

However API I have to work with response always with:

{
    "data": [] // array contains objects
}

I only found the way1 to change namespace or URL for the API. How to tell REST adapter to look for data instead of messages property?

If this is not possible how to solve this problem? CTO said we can adapt API to use with REST adapter as we want, but from some reason we can't change this data property which will be on each response.

Upvotes: 0

Views: 975

Answers (1)

Toran Billups
Toran Billups

Reputation: 27407

Assuming you are ok with writing your own adapter to deal with the difference, in the success callback you can simply modify the incoming name from "data" to your specific entity -in the case above "messages"

I do something like this to give you and idea of what if possible in a custom adapter

In the link below I highlighted the return line from my findMany

The json coming back from my REST api looks like

[
    {
        "id": 1,
        "score": 2,
        "feedback": "abc",
        "session": 1
    },
    {
        "id": 2,
        "score": 4,
        "feedback": "def",
        "session": 1
    }
]

I need to transform this before ember-data gets it to look like this

{
    "sessions": [
        {
            "id": 1,
            "score": 2,
            "feedback": "abc",
            "session": 1
        },
        {
            "id": 2,
            "score": 4,
            "feedback": "def",
            "session": 1
        }
    ]
}

https://github.com/toranb/ember-data-django-rest-adapter/blob/master/packages/ember-data-django-rest-adapter/lib/adapter.js#L56-57

findMany: function(store, type, ids, parent) {
    var json = {}
    , adapter = this
    , root = this.rootForType(type)
    , plural = this.pluralize(root)
    , ids = this.serializeIds(ids)
    , url = this.buildFindManyUrlWithParent(store, type, ids, parent);

    return this.ajax(url, "GET", {
      data: {ids: ids}
    }).then(function(pre_json) {
      json[plural] = pre_json; //change the JSON before ember-data gets it
      adapter.didFindMany(store, type, json);
    }).then(null, rejectionHandler);
},

Upvotes: 1

Related Questions