Serialization in Node REST APIs

twitter logo github logo ใƒป1 min read

One of the things I learned a while back was that database columns should not be mapped directly to the JSON responses an API serves (columns can change, backward compatibility etc).
There should be some layer of separation between the logic of forming the response and fetching/querying it.
In Rails we have Active Model Serializers and the new fast_jsonapi gem from Netflix. Is there a widely-used analogous package for Node or some best practices that large-scale organizations using Node (like Ebay, Paypal, Netflix etc) employ?
Assuming we're talking about an API built up on Express.

twitter logo DISCUSS (2)
markdown guide

When it comes to serialising to JSON, I don't think there's a better option than JSON.stringify() in Node, which is what response.json() uses in express, by the way.

If you need to map database objects to response objects, you don't really need to pull in a library, you can just write a function to do any data transformation you need.

const mapPonyToResponse = (pony) =>
    gender: pony.gender || 'female',
    type: types[pony.type].human_readable,
    // And so on.

Django Rest Framework handles this layer of abstraction nicely

Classic DEV Post from Sep 2

What do you think of minimalist UI?

Usama Ashraf profile image
I'm a multilingual developer and architect who's trying to build impactful software everyday.

Do you prefer sans serif over serif?

You can change your font preferences in the "misc" section of your settings. โค๏ธ