[kbn/server-route-repository] Make params optional for Zod schema with only optional keys #191709
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
io-ts
andzod
have differences in how they usually define optional keys.In
io-ts
, we usually define a union between a type and a partial, and if all keys are optional we only provide the partial type.While in
zod
if all keys are optional, it's more common to simply put each key as optional while the wrapping object is not.The way the type inference works in the route repository leads to this two cases having different results.
For
io-ts
, when it sees a partial, it marks the query/path/body and thus params object as fully optional, while forzod
since query/path/body are not optional but all their keys are, the chain is still marked as required.This PR aims to align these behaviours by checking if the
zod
schema only specifies optional field, and if it does it marks the query/path/body level as optional so that params also can become optional.This way, when calling the API via the client, if all params are optional, the second options argument can be omitted.
Similarly, the types in the handler are marked correctly as possibly undefined to prevent bugs.
The PR also adds a little
isHttpFetchError
helper with slightly better type support than what the Core version has.