dry-rb / dry-schema

Coercion and validation for data structures
https://dry-rb.org/gems/dry-schema
MIT License
424 stars 110 forks source link

JSON schema array length definition (min|maxItems) issue #481

Open qd3v opened 1 month ago

qd3v commented 1 month ago

Describe the bug

This is probably more a feature request, or unexpected behavior detected. The hash validated correctly, but JSON schema generated is incorrect. For arrays there are special min|maxItems JSON schema rules, which dry-schema just replace with rules for strings

To Reproduce

Test = Dry::Schema.JSON do
  # As docs say: To add array predicates, use the full form:
  required(:users).value(:array?, min_size?: 5, max_size?: 5).each(:str?)
end

# spec

example "JSON schema match expected" do
  schema = <<~JSON.then { JSON.parse(it, symbolize_names: true) }
    {
      "$schema": "http://json-schema.org/draft-06/schema#",
      "type": "object",
      "properties": {
        "users": {
          "type": "array",
          "minItems": 5,
          "maxItems": 5,
          "items": {
            "type": "string"
          }
        }
      },
      "required": ["users"]
    }
  JSON

  expect(Test.json_schema).to eq(schema)
end

Output diff:

{
   $schema: "http://json-schema.org/draft-06/schema#",
   type: "object",
   properties: {
     users: {
       type: "array",
-       minItems: 5,
-       maxItems: 5,
       items: {
+         minLength: 5,
+         maxLength: 5,
         type: "string"
       }
     }
   },
   required: [
     "users"
   ]
}

Expected behavior

I'm using dry-schema for years, (thanks for great work!) and I understand its primary goals (validate ruby structures) and JSON schema gen is just a bonus, so this is the first time I found the missing feature would be nice to have.

My environment