Skip to content

Commit

Permalink
Fix json-schema type of maybe array
Browse files Browse the repository at this point in the history
  • Loading branch information
tomgi authored and flash-gordon committed Jan 6, 2025
1 parent bcb20c7 commit 3b32937
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 2 deletions.
4 changes: 2 additions & 2 deletions lib/dry/schema/extensions/json_schema/schema_compiler.rb
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ def visit_set(node, opts = EMPTY_HASH)
target_info = opts[:member] ? {items: target.to_h} : target.to_h
type = opts[:member] ? "array" : "object"

keys.update(key => {**keys[key], type: type, **target_info})
merge_opts!(keys[key], {type: type, **target_info})
end

# @api private
Expand Down Expand Up @@ -210,7 +210,7 @@ def merge_opts!(orig_opts, new_opts)
orig_type = orig_opts[:type]

if orig_type && new_type && orig_type != new_type
new_opts[:type] = [orig_type, new_type]
new_opts[:type] = [orig_type, new_type].flatten.uniq
end

orig_opts.merge!(new_opts)
Expand Down
62 changes: 62 additions & 0 deletions spec/extensions/json_schema/schema_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,68 @@
end
end

context "when using maybe array types" do
include_examples "metaschema validation"

subject(:schema) do
Dry::Schema.JSON do
required(:list).maybe(:array).each(:str?)
end
end

it "returns the correct json schema" do
expect(schema.json_schema).to eql(
"$schema": "http://json-schema.org/draft-06/schema#",
type: "object",
properties: {
list: {
type: %w[null array],
items: {
type: "string"
}
}
},
required: %w[list]
)
end
end

context "when using maybe array types with nested properties" do
include_examples "metaschema validation"

subject(:schema) do
Dry::Schema.JSON do
required(:list).maybe(:array).each do
hash do
required(:name).value(:string)
end
end
end
end

it "returns the correct json schema" do
expect(schema.json_schema).to eql(
"$schema": "http://json-schema.org/draft-06/schema#",
type: "object",
properties: {
list: {
type: %w[null array],
items: {
type: "object",
properties: {
name: {
type: "string"
}
},
required: %w[name]
}
}
},
required: %w[list]
)
end
end

describe "filled macro" do
context "when there is no type" do
include_examples "metaschema validation"
Expand Down

0 comments on commit 3b32937

Please sign in to comment.