Search code examples
node.jsexpressjoi

I have a Joi schema and I want that when I do a POST method the id is included and required and with PUT method the id is not taken into account


I have a schema joi object:

const commonFields = {
  id: joi.string().required(),
  name: joi.string().required().min(5).max(50),
  nif: joi.string().length(9).required(),
  diet: joi.bool().required().strict(),
  vegetarian: joi.bool().required().strict(),
};

const aluno = joi.object({
  ...commonFields,
  num: joi
    .string()
    .required()
    .regex(/^\d{1,4}\/\d{2}$/),
  regime: joi.string().required().valid("externo", "interno"),
});

(...)

When i make a PUT request to update a user i want to ignore the field "id" but when i make a POST request i want to make it required.

I tried the following:

In schema I added alter() to the field "id":

  id: joi.string().alter({
    post: (schema) => schema.required(),
    put: (schema) => schema.forbidden(),
  }),

And in my functions i did this:

async function updateUser(req, res, type, db) {
  try {
    const { error } = requestValidation[type].validate(req.body, {
      context: { method: req.method }
    });
    
    if (error) {
      return res.status(400).send({ error: error.message });
    }

    const id = req.params.id;
    const { name, nif, vegetarian, diet } = req.body;
(..)

But when i call this function in my PUT endpoint to update a user and add the field id into the requesition body it doesn't throw an error like it should throw. The response should be like this when i add the id to the body:

{
    "error": "\"id\" is not allowed"
}

I want to ignore the id because I want to receive it by req.params.id. I may not be doing the best way but I'm open to new suggestions!


Solution

  • The documentation has an example using tailor with alter

    const { error } = requestValidation[type].tailor(req.method.toLowerCase()).validate(req.body, {
      context: { method: req.method }
    });