Monthly Archives: June 2015

What is the difference between adapters and serializers in Ember Data?

… a question that I asked myself several times and each time I was confronted with it again after not touching any adapter or serializer for weeks — finding myself again struggling to clearly define the boundaries between those two. It’s also hard to find a concise answer to this on the internet. The Ember Guides cover adapters, but not serializers.

Adapters

Adapters define how your app talks to your API. They tell your application how to request resources from your API, especially how to build the URIs to request them and save them to.

Quote from the Ember Data docs:

[...] one thing you should know is that Ember Data uses an object called an adapter to know how to talk to your server.

An adapter is just an object that knows how to translate requests from Ember Data into requests on your server. For example, if I ask the Ember Data store for a record of type person with an ID of 123, the adapter translates that into an XHR request to (for example) api.example.com/v3/person/123.json.

Adapters have methods like find and findMany that are called by Ember in order to send an ajax request to the server to get one or several pieces of data. The methods will call the method buildURL internally, which builds the URI of the corresponding resource on the server. The adapter also takes care of belongsTo relationships and translates them into nested URIs.

Same goes for the opposite direction, methods like createRecord translate your record.save() into an ajax request to POST to the server. Right before sending the request, the createRecord method calls the serializer…

Serializers

Serializers process the payload your application receives from the server. When the payload hits Ember for the first time, it first goes through the extract method before it touches anything else. Through customizing this method you can make the data look more like what your application expects. Also serializers can tell your application how to handle nested payloads.

When sending something to the server, serializers can also reverse the changes made when the data was received by implementing the serializeIntoHash method.

Summary

As a metaphor you can see it like this: Adapters are the dictionaries that tell your application how to talk to your API. Serializers are molds that can shape the data received from the API, so it fits exactly to what your models and the rest of your application expect.

A flow diagram could look like this:

Hope that helped. Correct me if you find any mistakes (-;