jsontypedef / json-typedef-codegen

A CLI tool that generates code from JSON Typedef schemas
https://jsontypedef.com/docs/tools/jtd-codegen
MIT License
160 stars 31 forks source link

Discriminator variant disapears when type name is overridden #65

Open g6123 opened 1 year ago

g6123 commented 1 year ago

This schema with custom type name in metadata field:

{
  "discriminator": "eventType",
  "mapping": {
    "USER_CREATED": {
      "metadata": {
        "typescriptType": "UserCreatedEvent",
        "pythonType": "UserCreatedEvent"
      },
      "properties": {
        "id": {
          "type": "string"
        }
      }
    },
    "USER_DELETED": {
      "properties": {
        "id": {
          "type": "string"
        },
        "softDelete": {
          "type": "boolean"
        }
      }
    }
  }
}

does not generate discriminated variant USER_CREATED:

export type Test = TestUserCreated | TestUserDeleted;

export interface TestUserDeleted {
  eventType: "USER_DELETED";
  id: string;
  softDelete: boolean;
}
@dataclass
class Test:
    event_type: 'str'

    @classmethod
    def from_json_data(cls, data: Any) -> 'Test':
        variants: Dict[str, Type[Test]] = {
            "USER_CREATED": TestUserCreated,
            "USER_DELETED": TestUserDeleted,
        }
        return variants[data["eventType"]].from_json_data(data)

    # ...

@dataclass
class TestUserDeleted(Test):
    id: 'str'
    soft_delete: 'bool'
    # ...