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

Correctly cast not map bodies (plug puts them under _json key) #470

Merged
merged 1 commit into from
Jul 7, 2022
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
16 changes: 5 additions & 11 deletions lib/open_api_spex/operation2.ex
Original file line number Diff line number Diff line change
Expand Up @@ -75,20 +75,14 @@ defmodule OpenApiSpex.Operation2 do
# Special case to handle strings or arrays in request body that come inside _json
# https://hexdocs.pm/plug/Plug.Parsers.JSON.html
defp cast_request_body(
%RequestBody{content: content},
body = %{"_json" => params},
request_body,
%{"_json" => body_params},
content_type,
components = %Components{}
) do
case content do
%{^content_type => media_type} ->
case Cast.cast(media_type.schema, params, components.schemas) do
{:ok, _} -> {:ok, body}
error -> error
end

_ ->
{:error, [Error.new(%{path: [], value: content_type}, {:invalid_header, "content-type"})]}
case cast_request_body(request_body, body_params, content_type, components) do
{:ok, body_params} -> {:ok, %{"_json" => body_params}}
error -> error
end
end

Expand Down
2 changes: 2 additions & 0 deletions test/operation2_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,8 @@ defmodule OpenApiSpex.Operation2Test do
)

assert %Plug.Conn{} = conn

assert conn.body_params == %{"_json" => [%{user: %{email: "foo@bar.com"}}]}
end

test "cast request body - invalid data type" do
Expand Down