mtth / avsc

Avro for JavaScript :zap:
MIT License
1.27k stars 147 forks source link

Using type.isValid() with a union of records #454

Closed rvallely closed 5 months ago

rvallely commented 6 months ago

Hello,

I'm testing a schema using the type.isValid method and I'm confused as to why it's failing to validate a union of records. This is the expect statement from my test file.

image

The errorHook logs out path: [ 'user' ] any: { firstname: 'sam', age: 28 } typeof any: object.

I'm wondering if I'm missing a step specific to a union of records? It correctly validates a union of primitive values and if I use just the Userone record instead of the union it validates correctly too. I'm a bit stumped as to what's going on. Any help would be much appreciated. The avsc version I'm running is 5.7.7.

NickKelly1 commented 6 months ago

You have to tell avsc which union member it is. In your case it's the union member named "UserOne". You do this by wrapping the union value under another object with a property whose name is the union members name. See example below. Sometimes wrapping isn't needed when the union members are easily distinguished (can't remember the rules but they are simple) but this is not the case for two record types. (there's also an option to turn off auto-wrapping).

{
  dirty: true,
  expires: ...,
  user: {
    UserOne: {
      firstname: "sam",
      age: 28
    }
  }
}
rvallely commented 6 months ago

Thanks for this! The test working as expected. Is this data formatting also required when you serialise this kind of data?

NickKelly1 commented 6 months ago

Is this data formatting also required when you serialise this kind of data?

yep, that's right