davidmdm / myzod

MIT License
315 stars 20 forks source link

Coercion enum results not saved for object validation #65

Closed jrvanderveen closed 1 year ago

jrvanderveen commented 1 year ago

I believe the coercion of object attributes is not being enabled correctly for enums.

EX:

    enum Color {
      red = 'red',
      blue = 'blue',
      green = 'green',
    }
    const colorSchemaObj = myzod.object({
      test: myzod.enum(Color, { coerce: 'lower' }).optional(),
    });
    const colorSchemaEnum =  myzod.enum(Color, { coerce: 'lower' })

    const colorObj = colorSchemaObj.parse({test: 'RED'}); // returns {test: 'RED'}
    const color = colorSchemaEnum.parse('RED'); // returns 'red'

Expected:

    .......
    const colorObj = colorSchemaObj.parse({test: 'RED'}); // returns {test: 'red'}
    const color = colorSchemaEnum.parse('RED'); // returns 'red'

The colorSchemaObj will have coercionTypeSymbol set to false which leads to using a parsing function that does not return an updated object but instead just looks for validation errors.

Not sure of the implications of this change but I am thinking that updating the EnumType constructor like this would work

this[coercionTypeSymbol] = this.defaultValue !== undefined 

-> 

this[coercionTypeSymbol] = this.defaultValue !== undefined || this.coerceOpt !== undefined;
davidmdm commented 1 year ago

@jrvanderveen you are correct!

That's a good catch.

I have since pushed a new patch version 1.10.1 with this fix. Thanks for pointing it out!

Will close the issue now but feel free to reopen it if it is not resolved as you expected.

jrvanderveen commented 1 year ago

Awesome! Thanks for the quick turnaround!