input parameter of GET endpoint incorrectly parses a single-item array as a string #3046
Unanswered
tbrockmeyer-a
asked this question in
Q&A
Replies: 1 comment
-
|
Hello @tbrockmeyer-a Please review this short article: So, when you say |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
To preface - nice lib! This is something I was looking for many years ago, and in the past, I wrote my own half-assed versions of just this before I learned that nice things like zod existed. It's like the lib I was always wanting to build haha.
Description
Anyway, I did find one issue while trying to build up a basic API:
If you call a GET endpoint that has a zod input parameter which is an array of strings,passing only a single value nets you an input validation error. It claims that you've passed a string when an array was expected, but then how can you pass an array with only one value?
Expected
I expect that if the generated documentation is capable of detecting that an array of strings is expected, then the input validation logic should also be able to detect the same thing, and make decisions based on that.
Given that an array is expected, it follows that if only a single string is sent as input, it should be treated as an array with only one element instead of a plain string.
Reproduction
Given this endpoint setup:
And this test:
I get the following error:
{ "status": "error", "error": { "message": "names: Invalid input: expected array, received string" } }Contrast that with the following, where multiple values are provided:
There is no issue with this one, since when it sees multiple values, it assumes array by default.
{ "status": "success", "data": { "users": [ { "id": 1 } ] } }Workaround
By setting up any arrays as
string[] | string, and then supplying a transformation function for handling the case where the value comes as astring, all cases can be handled well. This also handles the case where the client sendsnames=joe,bobinstead ofnames=joe&names=bob, so both cases function correctly. Likely I would need this transformation function regardless, so I guess it's fine, but the type union makes it a little funky.Context
express-zod-apiversion: 25.5.3Beta Was this translation helpful? Give feedback.
All reactions