The neglected benefits of Ember Data Transform
“Action” is something like a Todo item that has a status.
In the database we are storing
action status as a numeric value e.g. 0 = “to do”, 10 = “in progress” and so on. This is a great and efficient way to store the data but when it comes to using it within our frontend application code we quickly found ourselves with a few cryptic
if statements piling up.
Here’s an example from a template:
Now, we could add extra comments and people that worked on that code would kind of sort of remember what those numbers mean while they are on the project. However, we all know that magical moment when someone else has to do some work on it is inevitable 😵
When you have some sort of value stored in the database that has to have meaning to a user it is best to map it to something meaningful within the code. This is where DS.Transform comes in. It is very straight forward to use as it only has
deserialize methods that you need to implement.
Let’s take our example from above and utilise the power of DS.Transform.
First we will create our meaningful constants.
Now that we have the constants let’s utilise them to define a custom Ember Data attribute by creating the
What happens above is we simply find the right status constant object by its
value attribute in the
deserialize method and return the result. When it is time to send it back to the server Ember Data will use the
serialize method where we simply return the
value attribute of the constant 💥
And the last thing we need to do is to specify the custom attribute in the
status attribute on the
action model is now the object we defined in the constants.
The cryptic numbers are now readable 🎉
The readability isn’t the only benefit. We now have a great place to add extra meta data against those statuses. For example, if we need to display a list of statuses for users to select from, we would need a readable label for each status.
Back to the constants 🏇. Let’s add
label attribute to each one and add a
STATUSES constant which combines all statuses for convenience and can be used as a list of options.
And use it in a template:
As you can see, we now have meaningful statuses throughout the code with a place to add relevant meta data in the future 🦑
In the last year, we have doubled our team and expanded into more offices around the world. To enable our extreme scale to continue, our Sydney and Townsville teams need Software Engineers to drive our products forward. Check out our openings.