Skip to content

Commit

Permalink
do not use oneOf for single constructor data type
Browse files Browse the repository at this point in the history
  • Loading branch information
lostbean committed Dec 2, 2024
1 parent 09c1ef3 commit 77b40b0
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 7 deletions.
25 changes: 18 additions & 7 deletions src/json/blueprint.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -184,18 +184,29 @@ pub fn union_type_decoder(
|> result.flatten
}

#(
enum_decoder,
list.map(decoders, fn(field_dec) {
let #(name, dec) = field_dec
let schema = case decoders {
[] -> jsch.Object([], Some(False), None)

[#(name, dec)] ->
jsch.Object(
[#("type", jsch.Enum([json.string(name)])), #("data", dec.1)],
Some(False),
Some(["type", "data"]),
)
})
|> jsch.OneOf,
)

xs ->
list.map(xs, fn(field_dec) {
let #(name, dec) = field_dec
jsch.Object(
[#("type", jsch.Enum([json.string(name)])), #("data", dec.1)],
Some(False),
Some(["type", "data"]),
)
})
|> jsch.OneOf
}

#(enum_decoder, schema)
}

/// Function to encode an enum type (unions where constructors have no arguments) into a JSON object.
Expand Down
7 changes: 7 additions & 0 deletions test/json_blueprint_test.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -659,4 +659,11 @@ pub fn drawing_test() {
"{\"type\":\"box\",\"data\":{\"width\":15.0}}"
|> blueprint.decode(using: drawing_decoder())
|> should.be_error()

drawing_decoder()
|> blueprint.generate_json_schema
|> json.to_string
|> should.equal(
"{\"$schema\":\"http://json-schema.org/draft-07/schema#\",\"required\":[\"type\",\"data\"],\"additionalProperties\":false,\"type\":\"object\",\"properties\":{\"type\":{\"enum\":[\"box\"]},\"data\":{\"required\":[\"width\",\"height\",\"position\"],\"additionalProperties\":false,\"type\":\"object\",\"properties\":{\"width\":{\"type\":\"number\"},\"height\":{\"type\":\"number\"},\"position\":{\"maxItems\":2,\"minItems\":2,\"prefixItems\":[{\"type\":\"number\"},{\"type\":\"number\"}]},\"color\":{\"required\":[\"enum\"],\"additionalProperties\":false,\"type\":\"object\",\"properties\":{\"enum\":{\"enum\":[\"red\",\"green\",\"blue\"]}}}}}}}",
)
}

0 comments on commit 77b40b0

Please sign in to comment.