user3462947 user3462947 - 6 months ago 27
Node.js Question

Node.js RESTful api. Response after post issue

learning Node.js and trying to create rest api.
Now have this kind of services:

this.get = function (res) {
connection.acquire(function(err, con) {
con.query('select * from todo_list', function(err, result) {
con.release();
res.send(result);
});
});
};

this.create = function (todo, res) {
connection.acquire(function(err, con){
con.query('insert into todo_list set ?', todo, function(err, result){
con.release();
if(err) {
res.send({status: 1, message: "Todo creation failed"});
} else {
res.send({status: 0, message: "Todo created successfully"});
}
});
});
};


Question: how to return json on succesfull creation, for example:

{status: 0, message: ... , todos: [{id:1, name: 'Todo', date:...},{id:2, name: 'Todo', date:...}]}

Answer

Use res.json():

res.json({status: 0, message: "Todo created successfully"});

In order to include the todo items in the response, you'll have to make another database call. Instead of duplicating the code for getting all todo items, you might want to create a separate function for obtaining the todo items without responding to the client.

this.getAllItems = function(callback) {
  connection.acquire(function(err, con) {
    con.query('select * from todo_list', function(err, result) {
      con.release();
      callback(result);
    });
  });
}

this.get = function (res) {
  this.getAllItems(function(result) {
    res.json(result);
  });
};

this.create = function (todo, res) {
  var self = this;
  connection.acquire(function(err, con){
    con.query('insert into todo_list set ?', todo, function(err, result){
      con.release();
      if(err) {
        res.json({status: 1, message: "Todo creation failed"});
      } else {
        self.getAllItems(function(items) {
          res.json({
            status: 0, 
            message: "Todo created successfully",
            todos: items
          });
        });
      }
    });
  });
};

Don't forget to add error handling, though. =)

Also, check out promises (Bluebird, for example) to avoid callback hell.

Comments