-1

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);
});
Xaarth
  • 1,021
  • 3
  • 12
  • 34
  • 1
    havent spent any time outside of postman with joi, but here is an example of how to do it with express validator https://github.com/alilland/nodejs-api/blob/master/src/routes/registerRoutes.js – alilland Jul 10 '21 at 01:02
  • 1
    having come from other languages to nodejs its highly important to validate every value received if you can, otherwise you are just asking for trouble. But, you will find that most new javascript developers and many of the ones that write blog posts do not validate their payloads, which is dangerous. The biggest concerns for software developers exist here, https://owasp.org/www-project-top-ten/ and XSS attacks are what you are attempting to avoid by validating fields. – alilland Jul 10 '21 at 01:06
  • thanks! looks like I have to create another schema just for patch requests to validate the user input instead of using `req.body` without validation. – Xaarth Jul 10 '21 at 10:04

1 Answers1

0

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);
});
Xaarth
  • 1,021
  • 3
  • 12
  • 34