Skip to content
Closed
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
8 changes: 7 additions & 1 deletion lib/open_api_spex/cast/utils.ex
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,21 @@ defmodule OpenApiSpex.Cast.Utils do

# Merge 2 maps considering as equal keys that are atom or string representation
# of that atom. Atom keys takes precedence over string ones.
# Struct arguments are demoted to plain maps first: composite casts
# (`allOf`/`anyOf`) can receive struct results from `oneOf`/discriminator
# members, and reducing over a struct raises `Protocol.UndefinedError`.
def merge_maps(map1, map2) do
result = Map.merge(map1, map2)
result = Map.merge(plain_map(map1), plain_map(map2))

Enum.reduce(result, result, fn
{k, _v}, result when is_atom(k) -> Map.delete(result, to_string(k))
_, result -> result
end)
end

defp plain_map(%_{} = struct), do: Map.from_struct(struct)
defp plain_map(map), do: map

def check_required_fields(%{value: input_map} = ctx), do: check_required_fields(ctx, input_map)

def check_required_fields(ctx, %{} = input_map) do
Expand Down
8 changes: 8 additions & 0 deletions test/cast/all_of_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,14 @@ defmodule OpenApiSpex.CastAllOfTest do
"Failed to cast value as Age. Value must be castable using `allOf` schemas listed."
end

test "allOf wrapper around a oneOf member whose branch casts to a struct" do
union = %Schema{oneOf: [OpenApiSpexTest.Schemas.User.schema()]}
schema = %Schema{allOf: [union]}
value = %{"name" => "Joe", "email" => "joe@example.com", "password" => "12345678"}

assert {:ok, %{name: "Joe"}} = cast(value: value, schema: schema)
end

test "a more sophisticated example" do
dog = %{"bark" => "woof", "pet_type" => "Dog"}
TestAssertions.assert_schema(dog, "Dog", OpenApiSpexTest.ApiSpec.spec())
Expand Down