Search code examples
node.jsexpressjoi

Express - Validation for Patch Requests


I'm a front-end dev trying to create the rest api for my project with Node/Express.

I'm using Joi for validtion. I'm curios how can I PATCH request routes. I cannot use Joi because it says this field is required.

so I'm wondering how can I validate PATCH request routes. because I don't know what data I'll get. what could go wrong by using req.body without validation?

export const updateAccount = asyncHandler(async (req, res) => {
  let values = req.body;

  if (req.method === 'PUT') {
    values = await accountSchema.validateAsync(req.body);
  }

  const account = await Account.findByIdAndUpdate(req.params.id, values, {
    new: true,
  });

  if (!account) {
    return res.status(404).json({ message: 'Account not found' });
  }

  res.status(200).json(account);
});

Solution

  • As @aliland mentioned and also following Never trust user input. I've created a new Joi schema just for patch requests. because with the current schema it was complaining about the required fields.

    my schema:

    const accountSchemaForPatchRequests = Joi.object({
      firstName: Joi.string().min(3).max(30),
      lastName: Joi.string(),
      email: Joi.string().email(),
      password: Joi.string().min(8),
    });
    

    and controller:

    export const updateAccount = asyncHandler(async (req, res) => {
      let values = req.body;
    
      if (req.method === 'PUT') {
        values = await accountSchema.validateAsync(req.body);
      } else {
        values = await accountSchemaForPatchRequests.validateAsync(req.body);
      }
    
      const account = await Account.findByIdAndUpdate(req.params.id, values, {
        new: true,
      });
    
      if (!account) {
        return res.status(404).json({ message: 'Account not found' });
      }
    
      res.status(200).json(account);
    });