Search code examples
node.jsrestexpressput

How to control a PUT request with NodeJS Express


I need to set a ReST API with my NodeJS Express 4 Application.

Currently, this is my API.

I have a families resource which exposes several HTTP verb.

GET to perform a read in my MongoDB database. GET with familyID to get the family with the id familyID POST to create a new family in the database. PUT to update a family.

I want to follow the ReSTful theory so I'd like to control when a PUT is done that all the resource is modified and not a part of it (which is a PATCH verb).

This my nodejs route controller code :

// Main Function
router.param('famillyId', function(req, res, next, famillyId) {
// typically we might sanity check that famillyId is of the right format
Familly.findById(famillyId, function(err, familly) {
if (err) return next(err);
if (!familly) {
  errMessage = 'familly with id ' + famillyId + ' is not found.';
  console.log(errMessage);
  return next(res.status(404).json({
    message: errMessage
  }));
  }
  req.familly = familly;
  next();
  });
});

/PUT
router.put('/:famillyId', function(req, res, next) {
console.log('Update a familly %s (PUT with /:famillyId).', req.params.famillyId);

req.familly.surname = req.body.surname;
req.familly.firstname = req.body.firstname;
req.familly.email = req.body.email;
req.familly.children = req.body.children;

req.familly.save(function(err, familly) {
  if (err) {
    return next(err);
  }
  res.status(200).json(familly);
  });
});

I'd like to know what is the best way to do this control. I don't want to use a series of 'if' for each record of my JSON object. Is there an automatic way of doing it ? Just to avoid this kind of code :

if (req.familly.surname)
  if (! req.body.surname)
    return next(res.status(200).json('{"message":"surname is mandatory"}‘)));

Doing this kind of things for each property in my JSON Object is very boring, lots of code to type for nothing.

I looking forward a clean code to do it.

Thanks.

Hervé


Solution

  • var control = ['surname', 'firstname', 'email', 'children'];
    
    control.forEach(function(arg){
      if(!req.body[arg]){
        return next(res.status(200).json({"message": arg + " is mandatory"}));
      }
    });