Only Update Certain Fields on Put Restify + SQLite3

149 views Asked by At

I am using Restify with a SQLite3 database. So far this is what I have for my put method:

server.put('/users/:userid', function(req, res, next) {
  bcrypt.hash(req.body.password, 10, function(err, hash) {
    if (err) {
      res.send(err);
    } else {
      db.run('UPDATE users SET username = ?, first_name = ?, last_name = ?, email = ?, password = ? WHERE id = ?', req.body.username, req.body.first_name, req.body.last_name, req.body.email, hash, req.params.userid, function(err) {
        if (err) {
          res.send(err);
        } else {
          res.json({ message:'Successfully updated user'});
        }
      });
    }
  });
  next();
});

In order for this to work one would have to pass in every attribute again:

{
    "username": "greg",
    "first_name": "Greg",
    "last_name": "Davis",
    "email": "[email protected]",
    "password": "password"
}

Obviously this is redundant if only the email needs to be changed. How could I modify my code so that passing in the following would be enough?

{
    "email": "[email protected]",
}

I am okay adding in some additional logic to check if a new password is specified, as that more complicated, but adding in logic for every single field seems excessive.

1

There are 1 answers

0
HeadCode On BEST ANSWER

Instead of using raw DB queries you might look into using something like Sequelize, which is compatible with sqlite3. You could then retrieve the user object, make only the needed changes and then run update on the object.

Otherwise it looks like creating if statements for every possible field is in order.