Saturday, May 16, 2015
Deserialization in Ember Data (CLI edition May 2015)
I was working on a side project to learn Ember JS recently and hit a major roadblock with deserializing data from a REST API. I have a model that looks like this:
Ember therefore expects a JSON payload that looks like this:
However, the API (from Kimono) actually returns a payload with the people array embedded within a results array:
I spent hours trying to figure out how to use the deserialize methods to extract the people array from the results array. What frustrated me was that I couldn't really find any examples of how to use the deserialize methods. Maybe it's super basic for most people but I'm an Ember noob and couldn't figure it out for ages.
To help you avoid my teeth gnashing, here's the code I wrote for my serializer.
To explain what's going on here, we have to override a few methods: extractSingle (if there's only one person returned), extractArray (if you used findAll) and normalizeHash (used by both of the two previous methods).
extractSingle and extractArray are frustratingly simple. To look at them, you'd think it took me 5 minutes to write the code not 4 hours hahaha! Hopefully you'll find it super easy to write deserializers now.
The key things to note are that you can delete elements from the payload, e.g. delete payload.results; In this case, I completely overrode the payload as the only thing that I needed was the people array.
Something else to be mindful of is that if the API has different variable names to your model, you can add a new variable name to the hash (e.g. hash.fullName = hash.name;) and then delete the old variables.
It does seem to be relatively important to clean up unused variable names because otherwise Ember warns you about variables that aren't found in the model. It won't break your application but it does make your console messier than it needs to be.
Hope this little guide helps! Let me know if you have any questions.