kadrian
kadrian

Reputation: 5009

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

before I return it from the API as JSON.

Similar to what these Rails libraries do:

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.

Upvotes: 5

Views: 3140

Answers (4)

lyfeyaj
lyfeyaj

Reputation: 31

This module will helper you with Grape Entity manner:

https://github.com/baijijs/entity

For example:

const Entity = require('baiji-entity');

const userEntity = new Entity({
  id: true,
  fullname: true,
  email: true,
  data: true
});

userEntity.parse(req.user);

// And the parsed result will be as below

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

Hope this can help you.

Upvotes: 2

unseen_damage
unseen_damage

Reputation: 1376

Without knowing more details about the setup, the following (untested) code has the potential to work. You could specify the attributes field in your query against the model in order to filter out results (based on certain conditions):

router.get('me/data',function(req, res) {
   db.UserModel.find({
     attributes:['id','first_name','last_name','email','data'],
     where: { id: req.user.id}, //put in here whatever you are using to get the info from the database
    })
    .then (function(user) {
        var formatUser = {
            id: user.id,
            full_name: user.first_name + ' ' + user.last_name,
            email: user.email,
            data: user.data,
        };
        res.json(formatUser);
    }
 });

See the following docs for more information:

http://docs.sequelizejs.com/en/latest/docs/models-usage/

http://docs.sequelizejs.com/en/latest/docs/querying/

Upvotes: 0

DrakaSAN
DrakaSAN

Reputation: 7853

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);
    });
  }
);

Upvotes: 2

Sprotte
Sprotte

Reputation: 541

Ok so you would like to chop of some of the fields? You could chop it of before the server is sending the response. For example with a module like this https://www.npmjs.com/package/json-chop or if you use mongo db you can hide the fields like described here https://docs.mongodb.org/manual/tutorial/project-fields-from-query-results/

Upvotes: 0

Related Questions