joi icon indicating copy to clipboard operation
joi copied to clipboard

joi.object().optional() doesn't accept empty object anymore?

Open Saeger opened this issue 2 years ago • 5 comments

Context

  • node version: 14
  • module version: 17.6.0
  • environment (e.g. node, browser, native): node
  • used with (e.g. hapi application, another framework, standalone, ...): standalone
  • any other relevant information:

How can we help?

Hi,

I think I might be facing a breaking change from Joi version 12 to 17.6.0 where doing joi.object().optional() no longer supports me to pass the validation when having an empty object (without keys) like {}

Below is my failed validation, where i pass q={} and sort={}

{
  "statusCode": 400,
  "message": "Validation failed",
  "errors": [
    {
      "message": "\"q\" must be of type object",
      "path": [
        "q"
      ],
      "value": "{}"
    },
    {
      "message": "\"sort\" must be of type object",
      "path": [
        "sort"
      ],
      "value": "{}"
    }
  ]
}

Any suggestion on how I should be handling this, as I don't know the keys by default (they're unknown) and is still fine if you pass an empty object like {} ?

    q: joi.object().optional(),
    sort: joi.object().optional(),

Saeger avatar Mar 31 '22 12:03 Saeger

Can't say it's reproducible https://runkit.com/embed/kt9ta42pxzbq

Marsup avatar Apr 05 '22 09:04 Marsup

const querySchema = {
  query: joi.object().keys({
    q: joi.object().optional(),
    sort: joi.object().optional(),
  }),
};

...

router.get(
  '/',
  validate(querySchema),

This is how I do and then i get the validation error when doing a post http://dazzler.minikube/api/management/v2/users?q={}&sort={}

  "statusCode": 400,
  "message": "Validation failed",
  "errors": [
    {
      "message": "\"q\" must be of type object",
      "path": [
        "q"
      ],
      "value": "{}"
    },
    {
      "message": "\"sort\" must be of type object",
      "path": [
        "sort"
      ],
      "value": "{}"
    }
  ]
}```

Saeger avatar Apr 05 '22 09:04 Saeger

Oh, this is a query string. Then I guess you should read the 16.0.0 release notes, specifically the part about Array and object string coercion.

Marsup avatar Apr 05 '22 09:04 Marsup

Thanks for the replies @Marsup . I understood that I could restore the old behaviour in this case, but what would be the path to support objects in query string with our current joi in this case? Maybe I should adapt so I don't keep legacy code.

Saeger avatar Apr 05 '22 09:04 Saeger

You mean if you want it globally? You should create a custom joi and share it across the app.

Marsup avatar Apr 05 '22 10:04 Marsup

I feel like we're done here, reopen if you still need help.

Marsup avatar Sep 12 '22 22:09 Marsup