Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix json-schema type of maybe array #463

Merged
merged 1 commit into from
Jan 6, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ -108,6 +108,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