Using Joi to override param value

Viewed 237

I'm using Joi to validate params for a function that has the purpose to create pagination metadata. The function receives the following params totalItemsNum, skip, and limit. I'm trying to achieve the following scenario:

1 - When totalItemsNum is equal to 0, Joi should set the value of the skip param to zero regardless of the original value.

2 - When totalItemsNum is not zero, Joi should not let the skip param be equal or greater than totalItemsNum. So if skip is equal or greater than totalItemsNum, Joi should set the value of the skip param to totalItemsNum - 1.

I manage to achieve that with the following code:

  const validator = Joi.object({
    totalItemsNum: Joi
      .number()
      .min(0)
      .required(),
    skip: Joi
      .number()
      .when('totalItemsNum', [
        {
          is: 0, 
          then: Joi
            .number()
            .optional()
            .empty(Joi.number())
            .default(0)
        },
        {
          is: Joi.number().equal(Joi.ref('skip')), 
          then: Joi
            .number()
            .optional()
            .empty(Joi.number())
            .default((parent) => parent.totalItemsNum - 1)
        },
        {
          is: Joi.number().less(Joi.ref('skip')), 
          then: Joi
            .number()
            .optional()
            .empty(Joi.number())
            .default((parent) => parent.totalItemsNum - 1)
        },
      ]).required(),
    limit: Joi
      .number()
      .default(10)
  })

However, I have the impression that this code can be simplified. For instance, I'm always setting the skip as optional, to then set any number value to be recognized as an empty value with the empty(Joi.number()), to finally use default() to force the value I desire.

  1. Is there a way to use Joi to reassign a value instead of using Joi.default()?

  2. Is there a way to check in the same object if skip is greater or equal to totalItemsNum?

0 Answers
Related