huma icon indicating copy to clipboard operation
huma copied to clipboard

fix(schema): proper array minItems, maxItems and doc reporting in generated schemas

Open Grumpfy opened this issue 3 weeks ago • 1 comments

Hi!

We have a use case that can be summarised by:

// sRGB color space, normalized : R,G,B,A
type Color4f [4]float64

func (c Color4f) TransformSchema(r huma.Registry, s *huma.Schema) *huma.Schema {
	s.Description = "RGBA floating point color such as semi-transparent white is [1.0,1.0,1.0,0.5]"
	return s
}

type RequestParams struct {
	OptionalColor           *Color4f     `json:"optionalColor,omitempty"`
	RequiredColor          Color4f       `json:"requiredColor"`
}

Expected schema:

    "RequestParams": {
        "additionalProperties": false,
        "properties": {
          "optionalColor": {
            "description": "RGBA floating point color such as semi-transparent white is [1.0,1.0,1.0,0.5]",
            "items": {
              "format": "double",
              "type": "number"
            },
            "maxItems": 4,
            "minItems": 4,
            "type": "array"
          },
          "requiredColor": {
            "description": "RGBA floating point color such as semi-transparent white is [1.0,1.0,1.0,0.5]",
            "items": {
              "format": "double",
              "type": "number"
            },
            "maxItems": 4,
            "minItems": 4,
            "type": "array"
          }
        },
        "required": [
          "requiredColor"
        ],
        "type": "object"
      }

Actual schema:

     "RequestParams": {
        "additionalProperties": false,
        "properties": {
          "optionalColor": {
            "items": {
              "format": "double",
              "type": "number"
            },
            "type": "array"
          },
          "requiredColor": {
            "description": "RGBA floating point color such as semi-transparent white is [1.0,1.0,1.0,0.5]",
            "items": {
              "format": "double",
              "type": "number"
            },
            "type": "array"
          }
        },
        "required": [
          "requiredColor"
        ],
        "type": "object"
      }

We're currently missing the minItems and maxItems for both fields and the custom description is missing if the field is a pointer to the Color4f type.

This PR try to address this issue.

Summary by CodeRabbit

  • New Features

    • Improved schema processing to handle pointers to arrays more efficiently.
    • Enhanced schema generation to support minItems and maxItems tags for better validation.
  • Tests

    • Added tests for custom arrays and pointer arrays with descriptions to ensure robust schema validation.

Grumpfy avatar Jun 20 '24 09:06 Grumpfy