Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

type clone() with wrapUnions does not work? #98

Closed
aidanbon opened this issue Apr 29, 2017 · 1 comment
Closed

type clone() with wrapUnions does not work? #98

aidanbon opened this issue Apr 29, 2017 · 1 comment

Comments

@aidanbon
Copy link

Following the discussion at #16 and cut and paste the sample code mentioned in the stackoverflow (see below), I expect the cloned value is in wrapped format, but turns out it is still unwrapped?! Do I miss something?

Here's the cut-n-paste from the stackoverflow discussion:
http://stackoverflow.com/questions/33236284/how-to-convert-a-json-object-into-avro-object-if-avro-schema-contains-union-in-i/33622239#33622239

var avsc = require('avsc');

var type =  avsc.parse({
  "type":"record",
  "name":"DataFlowEntity",
  "namespace":"org.sdf.manage.commons.server",
  "fields": [
    {"name":"dataTypeGroupName","type":["null","string"]},
    {"name":"dataTypeName","type":"string"},
    {"name":"dataSchemaVersion","type":"string"}
  ]
});

var invalidRecord = {
  "dataTypeGroupName": "dg_1",
  "dataTypeName": "dt_1",
  "dataSchemaVersion": "1"
};

var validRecord = type.clone(invalidRecord, {wrapUnions: true});
console.log(validRecord)

Expected cloned value as wrapped:

{
  "dataTypeGroupName":{"string":"dg_1"},
  "dataTypeName":"dt_1",
  "dataSchemaVersion":"1"
}

But the above code returns unwrapped result?!

{
  "dataTypeGroupName":"dg_1",
  "dataTypeName":"dt_1",
  "dataSchemaVersion":"1"
}
@mtth
Copy link
Owner

mtth commented Apr 29, 2017

It's because 5.0 changed the default wrapping behavior when parsing types: unions are now only represented wrapped where needed.

clone's wrapUnions option only takes effect when the underlying union is wrapped which isn't the case above since ["null", "string"] isn't ambiguous (take a look at the union types for a bit more information).

You can still force wrapping by explicitly setting parse's wrapUnions option though; here's a type that'll make your example work as expected:

var type =  avsc.parse({
  "type":"record",
  "name":"DataFlowEntity",
  "namespace":"org.sdf.manage.commons.server",
  "fields": [
    {"name":"dataTypeGroupName","type":["null","string"]},
    {"name":"dataTypeName","type":"string"},
    {"name":"dataSchemaVersion","type":"string"}
  ]
}, {wrapUnions: true});

I updated the example on Stack Overflow to reflect the change. Thanks for bringing it up!

@mtth mtth closed this as completed Apr 29, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants