ajv
ajv copied to clipboard
proposal: coerceTypes from strings only
What version of Ajv you are you using? 6.10.0
What problem do you want to solve?
I want to convert values from queryStrings and url paramters into to their proper type. CoerceTypes true and "array" seem too eager to make changes I don't want such as converting false to 0 and vice versa.
What do you think is the correct solution to problem?
Add a new option for coerceTypes, maybe "string" or "fromString".
Will you be able to implement it? Probably not soon.
or maybe coerceFromStringsOnly: true or more generic coerceFromTypes: ['string'] (although there is no use case for it).
Or just allow coerceTypes to be an array of types: coerceTypes: ['string', 'boolean', ...]
A question about string coercion: The current rule is that an empty string is coerced to null.
- How is the schema configured to trigger this coercion? If it set type to ['string', 'null'], then there is no coercion on an empty string. Only if type is 'null' does it work (which is fairly useless).
- A string of whitespace isn't coerced anyway. I realize ajv-keywords has a trim function, but shouldn't this string to null coercion treat whitespace as null, too? Maybe it should be an option?
Only if type is 'null' does it work.
Yes.
A string of whitespace isn't coerced anyway. I realize ajv-keywords has a trim function, but shouldn't this string to null coercion treat whitespace as null, too? Maybe it should be an option?
It's all outside of spec, so I am inclined to keep it as is.
Or just allow coerceTypes to be an array of types: coerceTypes: ['string', 'boolean', ...]
Maybe, but it will substantially complicate the logic... Thinking
I understand the desire to keep it "in spec" (which I'm a big fan of). That's what makes me uncomfortable with the avj-keywords extension (in that it adds out-of-spec props to the schema).
But trimming of all-whitespace strings seems like such a common function that I think it deserves an "options" prop (which doesn't touch the schema). I think it's really independent of coerceTypes, maybe something like "trimStrings:false|true"?
Then also, instead of complicating the coerceTypes prop, add a prop of "nullEmptyStrings:false|true"?
+1 for coerceTypes: ['string', 'boolean', ...]
Almost every time I don't need coercion of null.