Keeping your data models clean while still being able to extend it for your application with tcomb
Sometimes our API data structure is not enough for our UI implementation because it is lacking properties and what not.
Let’s assume that the data we’re getting from an API has the following structure — a list of employees that contain their first and last names.
Since we’re using tcomb, our data structure for this would be something like.
However, we want to display these employees in a HTML list that contains checkboxes — each employee can be selected. So now we have to track if either an employee is selected or not.
The problem that we now have is that an Employee does not have a selected property that says whether the employee has been selected or not.
So why not just add a selected attribute to your Employee structure? Well, we can’t. That’s because the struct combinator drops additional properties when we add them.
So how do we add additional properties without mutating the original data structure for an employee?
All struct constructors can be extended using the extend function. By using the extend function, we can now add an additional property to our employee.
Here’s a working example of it.
So not only did we avoid mutating our original data structure for Employee but we’re also able to solve our problem of not having a property to track if an employee has been selected or not.
Now what if we need to send back a list of selected employees?
Sending back a data structure that is quite different from what you received should always be avoided. We want the back-end services to know exactly what type of structure they’re about to receive. Everything else should be discarded.
tcomb makes it easy to transform your data back to it’s original form. Since we know that passing unknown properties get discarded when using struct. All we have to do is use the Employee struct and pass extendedEmployee as the argument. By doing so, the Employee struct will discard all the extra properties that we’ve added in ExtendedEmployee.
If you prefer to see some animation…
Now you can send your list of employees back to your back-end without having to worry that you’ve changed the data structure.