a-h / generate

Generates Go (golang) Structs from JSON schema.
MIT License
444 stars 137 forks source link

Root types aliases #40

Closed antoineco closed 6 years ago

antoineco commented 6 years ago

When a top-level schema is composed only of a simple type (anything but object), generate a type alias for it instead of ignoring it.

2 use cases come to my mind: adding methods to primitive Go types, and working with constants.

Example 1:

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "id": "http://foo",
  "type": "string",
  "enum": [ "A", "B" ]
}
// Code generated by schema-generate. DO NOT EDIT.

package main

// Root
type Root string

Example 2:

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "id": "http://foo",
  "type": "array",
  "title": "foos",
  "items": {
    "type": "object",
    "title": "foo",
    "properties": {
      "fieldA": {
        "type": "string"
      },
      "fieldB": {
        "type": "boolean"
      }
    }
  }
}
// Code generated by schema-generate. DO NOT EDIT.

package main

// Foos
type Foos []Foo

// Foo 
type Foo struct {
  FieldA string `json:"fieldA,omitempty"`
  FieldB bool `json:"fieldB,omitempty"`
}

➡️ Tests results