omissis / go-jsonschema

A tool to generate Go data types from JSON Schema definitions.
MIT License
558 stars 89 forks source link

Allow `CustomNameType`s to specify nillability #220

Closed andrew-farries closed 4 months ago

andrew-farries commented 4 months ago

Allow CustomNameTypes to specify their nillability.

Currently CustomNameTypes are hard-coded to have IsNillable return false. This limitation means that fields in an object having a custom type are always wrapped in a pointer type when they are not required fields. For example:

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "properties": {
    "name": {
      "type": "string",
      "goJSONSchema": {
        "type": "map[bool]string"
      }
    }
  }
}

This results in the following Go code:

type Nillability struct {
    // Name corresponds to the JSON schema field "name".
    Name *map[bool]string `json:"name,omitempty" yaml:"name,omitempty" mapstructure:"name,omitempty"`
}

The map[bool]string is nillable, but go-jsonschema's schema generation generates a pointer type for the name field.

By extending the GoJSONSchemaExtension type with an extra Nillable field, custom types can specify their nillability in order to ensure they aren't wrapped in a pointer type when such fields are optional.


The motivation for this change is to be able to use the nullable package to distinguish between set-to-null fields and missing fields.

This snippet:

        "name": {
          "type": "string",
          "goJSONSchema": {
            "imports": ["github.com/oapi-codegen/nullable"],
            "nillable": true,
            "type": "nullable.Nullable[string]"
          }
        },

Should generate a name field of type nullable.Nullable[string] rather than *nullable.Nullable[string], in line with the documentation for nullable which advises against using pointers to the type.

codecov[bot] commented 4 months ago

Codecov Report

Attention: Patch coverage is 66.66667% with 1 lines in your changes are missing coverage. Please review.

Project coverage is 75.94%. Comparing base (d963216) to head (27032aa). Report is 21 commits behind head on main.

Files Patch % Lines
pkg/generator/schema_generator.go 50.00% 1 Missing :warning:
Additional details and impacted files ```diff @@ Coverage Diff @@ ## main #220 +/- ## ========================================== - Coverage 76.58% 75.94% -0.65% ========================================== Files 24 26 +2 Lines 1892 1646 -246 ========================================== - Hits 1449 1250 -199 + Misses 354 298 -56 - Partials 89 98 +9 ```

:umbrella: View full report in Codecov by Sentry.
:loudspeaker: Have feedback on the report? Share it here.