Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize / represent database objects as JSON returned by API in node

I'm using express.js and sequelize.js to build an API. Once I retrieved an object from the DB using sequelize, I want to

  • filter out object attributes (e.g. retrieve the user, but don't render the User's password hash to the returned JSON)
  • add new object attributes

before I return it from the API as JSON.

Similar to what these Rails libraries do:

  • Roar
  • Grape Entity

What's the most common framework to do that in node? Or do sequelize.js / express.js contain functionality to do that?

UPDATE

Ok, there is a basic example, passport.js gets the authenticated user's object from the DB and attaches it to req.user;

router.get('/me/data',
  passport.authenticate('bearer', { session: false }),
  function(req, res) {
    res.status(200).send(req.user);
  }
);

That would return the following JSON response:

{
  "id": 24,
  "first_name": "John",
  "last_name": "Doe",
  "email": "[email protected]",
  "password": "8d23cb9c4827bc06bb30ac47c06af0efbdbeb575001ab7de5387da4085f7184a381335c0f04b45f4a40e5a7042d47ae1e2d29d28fd5be1d534f09ba3db04e8ca",
  "updatedAt": "2016-01-25T09:19:07.422Z",
  "createdAt": "2016-01-25T09:19:07.422Z",
  "data": null
}

But I want to return something like this:

{
  "id": 24,
  "full_name": "John Doe",
  "email": "[email protected]",
  "data": null
}

And not just for this one case, but in any case a user object is rendered.

like image 398
kadrian Avatar asked Sep 26 '22 14:09

kadrian


1 Answers

The simplest solution would be to edit req.user before sending it:

function

render (user) {
    callback({
        "id": user.id,
        "full_name": user.first_name + ' ' + user.last_name,
        "email": user.email,
        "data": null
    });
}

router.get('/me/data',
  passport.authenticate('bearer', { session: false }),
  function(req, res) {
    render(req.user, function(user) {
        res.status(200).send(user);
    });
  }
);
like image 149
DrakaSAN Avatar answered Sep 28 '22 05:09

DrakaSAN