"links" as property instead of returned in JSON payload


#1

I have finally found how to lazy load associated data from an Ember model. The thing I was missing was that the JSON should be returned in this format:

{
    "id": "032sqdf032qsd1f",
    "name": "Bob",
    "links": {
        "friends": "/users/032sqdf032qsd1f/friends"
    }
}

Ok, I get that now. However I was only able to achieve this by modifying the server’s response to add the “links” part through a local proxy. Now before you tell me to change the API, please not that this will just not be possible.

What would however be awesome is if I can define these links within Ember. Something like:

App.Person = DS.Model.extend({
    name: DS.attr('string'),
    friends: DS.hasMany('friend', {async: true}),
    links: {
        friends: function() {
            return "/users/" + this.get('id') + "/friends";
        }.property('id')
    }

});

The fact that “links” is called “links” and not for example “relations”, and that it must be on the retrieved in the payload from the server seems to be pretty nastily hardcoded inside of ember-data though. Is there any way around this?


#2

I have found this:

DS.Model.reopen({
    linkeRelationships: function() {
        if (this.links && !this._data.links) {
            this._data.links = _.result(this, 'links');
        }
    }.observes('data')
});

it “works”, but seems pretty inelegant… Also, what would happen if my object actually needs a collection of links that are not at all for data mapping. Like a wikipedia page through an api could very well have data like:

{
    "title": "Awesome Wiki Article",
    "content": "....",
    "links": {
        "external": {
            "a_reference": "http://...",
            "a_source": "http://..."
        }
    }
}

#3

@khepin are you still using this approach or have you found something that feels more elegant?