ajv icon indicating copy to clipboard operation
ajv copied to clipboard

proposal: coerceTypes from strings only

Open sparebytes opened this issue 6 years ago • 7 comments
trafficstars

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.

sparebytes avatar Jun 26 '19 06:06 sparebytes

or maybe coerceFromStringsOnly: true or more generic coerceFromTypes: ['string'] (although there is no use case for it).

epoberezkin avatar Jul 06 '19 13:07 epoberezkin

Or just allow coerceTypes to be an array of types: coerceTypes: ['string', 'boolean', ...]

Eric24 avatar Aug 19 '19 14:08 Eric24

A question about string coercion: The current rule is that an empty string is coerced to null.

  1. 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).
  2. 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?

Eric24 avatar Aug 19 '19 14:08 Eric24

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

epoberezkin avatar Aug 19 '19 15:08 epoberezkin

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"?

Eric24 avatar Aug 19 '19 15:08 Eric24

+1 for coerceTypes: ['string', 'boolean', ...]

Almost every time I don't need coercion of null.

redexp avatar Sep 22 '22 11:09 redexp