gcanti/tcomb-json-schema

Multiple types for struct attributes

Opened this issue · 0 comments

Hi,

first, thank you for your wonderful libraries. I have a problem using this package in combination with the objectionsjs orm. Objectionjs provides the ability to define a JSON schema for validation purposes on it's models. This would come in handy, because once this JSON schema is defined on a model, it can be reused with tcomb-forms and tcomb-json-schema to render the appropriate form for that model (only have to define it once).

Let's assume a JSON scheme like this:

const jsonSchema = {
      type: "object",
      properties: {
        id: { type: integer" },
        name: { type: "string" },
        series: { type: "string" }
      },
      required: ["name", "series"]
    };
  }

All good the below code renders the form perfectly fine.

 <t.form.Form
    ref="form"
    type={transform(jsonSchema)}
/>

The thing is that if the form is submitted and the values retrieved via this.refs.form.getValue(), the id field is populated with null what also seems reasonable.

console.log(this.refs.form.getValue());
-> Struct {id: null, name: "foo", series: "bar"}

My problem is that if I want to pass this data to my model for persisting the data, I get a validation error that the id attribute must be an integer but is null. Although, id is not required, setting it to null will trigger the validation and, therefore, spitting venom.

To circumvent this situation on the model side, I could define the JSON schema to something similar than the below and it would work so far:

const jsonSchema = {
      type: "object",
      properties: {
        id: { type: ["integer", "null"] },
        name: { type: "string" },
        series: { type: "string" }
      },
      required: ["name", "series"]
    };
  }

But now tcomb-form errors out:

Uncaught TypeError: [tcomb] Invalid value undefined supplied to Int | Null (no constructor returned by dispatch)
...

I suppose that tcomb-json-schema does not support this kind of double type setting? Do you see any light for an workaround or am I am just using your package the wrong way?

Edit: I have just discovered that this case of "unions" is covered in the unit tests (https://github.com/gcanti/tcomb-json-schema/blob/master/test/test.js#L388). Maybe that issue might be more related to tcomb-forms. Have to investigate and than I close this issue.