Skip to content

Commit

Permalink
Add complex nullable types
Browse files Browse the repository at this point in the history
Add a generic 'nullable*' type to allow maps and arrays to be nullable.

Example usage:

  Labels map[string]string `json:"labels" norman:"type=nullablemap[string]"`

Resulting API schema:

  "labels": {
    "create": true,
    "nullable": true,
    "type": "nullablemap[string]",
    "update": true
  }

Generated client code:

  Labels *map[string]string `json:"labels,omitempty" yaml:"labels,omitempty"`

Without this, because the generated client code uses "omitempty" JSON
tags, clients can't differentiate between an unset value and an empty
value. With this change, the generated client code becomes a map pointer
which allows clients to differentiate between sending `nil` and sending
`map[string]string{}`. The underlying type can still be a regular map.
  • Loading branch information
cmurphy committed May 19, 2021
1 parent e48df26 commit 4b8924a
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 4 deletions.
4 changes: 2 additions & 2 deletions generator/generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ func getTypeString(nullable bool, typeName string, schema *types.Schema, schemas
return "map[string]" + getTypeString(false, typeName[len("map["):len(typeName)-1], schema, schemas)
case strings.HasPrefix(typeName, "array["):
return "[]" + getTypeString(false, typeName[len("array["):len(typeName)-1], schema, schemas)
case strings.HasPrefix(typeName, "nullable"):
return "*" + getTypeString(false, typeName[len("nullable"):len(typeName)], schema, schemas)
}

name := ""
Expand Down Expand Up @@ -81,8 +83,6 @@ func getTypeString(nullable bool, typeName string, schema *types.Schema, schemas
return "string"
case "hostname":
return "string"
case "nullablestring":
return "*string"
default:
if schema != nil && schemas != nil {
otherSchema := schemas.Schema(&schema.Version, typeName)
Expand Down
4 changes: 2 additions & 2 deletions types/definition/definition.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@ import (
)

func IsMapType(fieldType string) bool {
return strings.HasPrefix(fieldType, "map[") && strings.HasSuffix(fieldType, "]")
return (strings.HasPrefix(fieldType, "map[") || strings.HasPrefix(fieldType, "nullablemap[")) && strings.HasSuffix(fieldType, "]")
}

func IsArrayType(fieldType string) bool {
return strings.HasPrefix(fieldType, "array[") && strings.HasSuffix(fieldType, "]")
return (strings.HasPrefix(fieldType, "array[") || strings.HasPrefix(fieldType, "nullablearray[")) && strings.HasSuffix(fieldType, "]")
}

func IsReferenceType(fieldType string) bool {
Expand Down

0 comments on commit 4b8924a

Please sign in to comment.