xddq / schema2typebox

Creating TypeBox code from JSON schemas
MIT License
54 stars 12 forks source link

throws on nullable objects #43

Closed smeijer closed 1 month ago

smeijer commented 1 month ago

Library version: 1.7.2

JSON schema version: draft-04, draft-06, draft-07, 2019-09, 2020-12

The current behavior

Parsing JSON schemas with nullable strings ["string", "null"] works, but it crashes on nullable objects ["object", "null"].

import { schema2typebox } from "schema2typebox";

const schema = JSON.stringify({
  type: "object",
  properties: {
    nullableObject: {
      type: ["object", "null"],
    },
    nullableString: {
      type: ["string", "null"],
    },
  }
});

await schema2typebox({ input: schema });

The expected behavior

Should not crash, but create a union.

export const T = Type.Object(
  {
    nullableObject: Type.Optional(Type.Union([Type.Object({}), Type.Null()])), // this one currently crashes
    nullableString: Type.Optional(Type.Union([Type.String(), Type.Null()])), // this one already works
  },
  { $id: "T" }
);

Why does it happen? What/How to fix the issue?

Content of minimal json schema file which causes the problem

Click to expand/collapse ```json { "type": "object", "properties": { "nullableObject": { "type": [ "object", "null" ] }, "nullableString": { "type": [ "string", "null" ] } } } ```