DEV Community

Usama Ashraf
Usama Ashraf

Posted on

Serialization in Node REST APIs

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.

Top comments (4)

Collapse
 
avalander profile image
Avalander

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) =>
  ({
    name: pony.name,
    gender: pony.gender || 'female',
    type: types[pony.type].human_readable,
    // And so on.
  })
Collapse
 
tschellenbach profile image
Thierry

Django Rest Framework handles this layer of abstraction nicely

Collapse
 
luvpreet33 profile image
luvpreet

Is there something similar available in express? maybe a separate library to do that?

Collapse
 
xenobino profile image
Ahmed

Create the file serializer/router.ts (or .js), create an object that has express.Router http verbs methods. In each http method, pass the user passed middleware alongside with your serialization middleware. Export it and use it as if you're using express.Router . In your routes call next() instead of sending a response and the middleware will handle the serialization. For serialization you can use any general serialization library or write you're own.