swaggest / jsonschema-go

JSON Schema mapping for Go
https://pkg.go.dev/github.com/swaggest/jsonschema-go
MIT License
112 stars 14 forks source link

Struct tags for array of enum values #26

Closed hrobertson closed 2 years ago

hrobertson commented 2 years ago

I have a field that is an array of enum values.

The OpenAPI spec to represent this is this:

"days": {
  "type": "array",
  "items": {
    "type": "string",
    "enum": [
      "Monday",
      "Tuesday",
      "Wednesday",
      "Thursday",
      "Friday",
      "Saturday",
      "Sunday"
    ]
  }
}

I can not find how this can be represented in a go struct tag. This does not work:

Days []string `json:"days" enum:"Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday"`

It results in this incorrect (invalid?) OpenAPI schema:

"days": {
  "enum": [
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday",
    "Sunday"
  ],
  "type": "array",
  "items": {
    "type": "string",
  }
}

Thanks

vearutop commented 2 years ago

Field tags apply to the property for which they are defined, that's why you get enum for days and not for days/items.

In such case (slice of strings) you can not use field tags to define enum, but you can either create a named type and implement Enum() []interface{} on it, or define schema preparer and set up enum in it.

Please check this example.

hrobertson commented 2 years ago

Thanks for the examples.