Ember JS : Creating nested urls for relationships REST-style

I’ve been working on a project in Ember JS with the Ember-client extension for a while now. Ember is very frustrating to work with because of the lack of documentation.

I was recently looking for a way to have Ember use urls for loading and saving resources from a REST-api using the same conventions used by api’s like the ones Facebook and Twitter use.

For example, requesting the comments for a post would have an endpoint like this:

/posts/{ID}/comments

Unfortunately Ember will just post the user id to this endpoint:

/comments

There is a way to have Ember use /posts/{ID}/comments as endpoint but that requires the payload from the api for a post to contain the property ‘links’, containing the desired endpoint. To me this seems undesirable; endpoints should be derived from conventions. Besides, if you have no control over the api then you have no control over this ‘links’ property

You could add the ‘links’ property to the payload by overriding Ember’s RESTAdapter or RESTSerializer but that is a difficult place to do that.

I analysed what Ember does in the background when it finds the ‘links’ property on a payload : it creates relationships in the corresponding model. I managed to create an override that changes the ‘link’ property of the corresponding relationship.

This is my code:

I’m not really happy with this solution because manually changing the ‘link’ property after ember created the relationship is far from ideal. But in the mean time, untill I find a better approach I’m sticking to this in order to get my application to work.

 

Published by

Justin

Justin

Hi there! I'm a software engineer currently employed at a company in The Hague in the Netherlands. You can find out more about me and my qualifications on LinkedIn (http://nl.linkedin.com/pub/justin-van-schaick/26/1b0/210). I started this blog in order to share interesting code snippets and tutorials on mainly Javascript, PHP and related frameworks. The internet is an invaluable resource for programmers and unfortunately there's never enough documentation out there. So this is me trying to contribute to that.

Leave a Reply