Custom Adapters for Ember Data

Published on Mar 04, 2014

Ember Data works really well with a RESTful API. But you have a problem: your server API was designed by a drunken ferret and is already being used by several other clients. How can you get Ember Data to work with it?

Code

Transcript

I was working on my new project, Facebook for Ferrets, and my controller was trying to find a ferret but it couldn't. The URL ferret/12 didn't match any routes that I had in my API. That's because I let my pet ferret define my API, so instead of a restful API, he created something a little bit different. We're going to investigate and see how we can change Ember to match the API.

We're going to start by seeing that we've used the rest adapter, so it'll expect a restful URL. This is how the rest adapter is defined and we have the find functionality, which creates an AJAX call to whatever is defined in ""Build URL." For my first implementation, I just decided to completely overwrite find with the URL that I needed.

However, as you can guess, the second that I wanted to do anything besides find a ferret, this created problems... so I used a custom adapter. The ferret adapter will only take effect when I'm trying to find a ferret. If I need to find an owner or the breed of mice, then I'll use the typical rest adapter, but if it's trying to find a ferret, it'll look for 12-ferretses. This is awesome.

However, we soon need to do more than call for just one ferret. We need to ask the server for all the ferrets. In a restful URL, it would just be /ferrets. However, my pet ferret has decided to store those at /wonderful/ferretses. If you call find without an ID or any arguments, eventually you'd go to find all in the rest adapter. Find all, as you can see, calls "Build URL."

As a matter of fact, a lot of things call "Build URL," not just find and find all, but find query, find many, find has many, find belongs to, create record, update record, and delete record. We could update all 9 of these things individually but that is exhausting. It's much better if you have an API that makes some sort of sense to just update "Build URL".

This, what you're seeing here, is the default implementation of "Build URL," which you can overwrite. If you can keep your API under some sort of control, it's better to use "Build URL" instead of overwriting every single one of those 9 that you use. However, even if you don't, Ember data still has your back.

Subscribe to our mailing list