CCPony CCPony - 4 months ago 12
reST (reStructuredText) Question

Using MassiveJS for REST put/post saves

Using current version of MassiveJS and express for API calls. When using the SAVE function, Massive wants a list of column names to update as follows:

router.put('/:id', function(req, res, next) {
db.suppliers.save(
{
id: +req.params.id,
name: req.body.name,
email: req.body.email,
column1: req.body.column1,
column2: req.body.column2,
column3: req.body.column3,
manyOtherColumns: req.body.manyOtherColumns,
etc...
}, function (err, result) {
if (err) {
return next(err);
}
return res.status(200).json({
status: 'SUCCESS',
message: 'Supplier has been saved'
});
})
});


As you can see, as the column list getting longer and longer, this code becomes more difficult to maintain. So I was wondering if there is a way to save the entire req.body in a single call assuming that the req.body key values match the db column names. That would save A LOT of time and be far more maintainable.

Answer

Massive isn't an ORM, so saving an "object" isn't the idea. If you want to update something you can do so directly using db.update and passing in the values you want updated as well as the id of the row. This will do a partial update for you.

As I mention in the comments, opening up a REST endpoint to update whatever a user sends in via POST is probably not a good idea, even if you do trust your user.

Finally: if you want to just pass along the form post you can:

router.put('/:id', function(req, res, next) {
  var supplier = {
    id: req.params.id;
  };
  supplier = _.extend(supplier, req.params.body);
  db.suppliers.save(
    supplier
    , function (err, result) {
      if (err) {
        return next(err);
      }
      return res.status(200).json({
        status: 'SUCCESS',
        message: 'Supplier has been saved'
      });
    })
});