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

Sub-errors of arrays are nested only one level. #8

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
21 changes: 12 additions & 9 deletions lib/formatters/ecto/changeset.ex
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,10 @@ defmodule DeliriumTremex.Formatters.Ecto.Changeset do
@spec format(error :: tuple()) :: Keyword.t()
def format({key, [%{} | _] = errors} = _error) when is_list(errors) do
errors = remove_empty_maps(errors)
human_key = humanize(key)

[
message: "#{human_key} errors",
key: key,
messages: nil,
full_messages: nil,
index: nil,
suberrors: Enum.map(errors, fn err -> format({key, err}) |> Enum.into(%{}) end)
]
Enum.reduce(errors, [], fn err, acc ->
merge_suberror_kw_lists(acc, format({key, err}))
end)
end

def format({key, errors} = _error) when is_list(errors) do
Expand Down Expand Up @@ -72,6 +66,15 @@ defmodule DeliriumTremex.Formatters.Ecto.Changeset do
Gettext.dgettext(DeliriumTremex.Gettext, "errors", msg, opts)
end

defp merge_suberror_kw_lists(kw_list1, kw_list2) do
Keyword.merge(kw_list1, kw_list2, fn key, v1, v2 ->
case key do
:suberrors -> Enum.concat(v1, v2)
_ -> v1
end
end)
end

defp remove_empty_maps(list_of_maps) do
Enum.filter(list_of_maps, fn x -> map_size(x) > 0 end)
end
Expand Down
34 changes: 16 additions & 18 deletions test/formatters/ecto/changeset_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -39,24 +39,22 @@ defmodule DeliriumTremex.Formatters.Ecto.ChangesetTest do

formatted_data = Changeset.format(data)

assert formatted_data[:suberrors] == [
%{
full_messages: nil,
index: nil,
key: :comments,
message: "Comments errors",
messages: nil,
suberrors: [
%{
full_messages: ["User_id does not exist"],
index: nil,
key: :user_id,
message: "User_id does not exist",
messages: ["does not exist"],
suberrors: nil
}
]
}
assert formatted_data == [
message: "Comments errors",
key: :comments,
messages: nil,
full_messages: nil,
index: nil,
suberrors: [
%{
full_messages: ["User_id does not exist"],
index: nil,
key: :user_id,
message: "User_id does not exist",
messages: ["does not exist"],
suberrors: nil
}
]
]
end
end
Expand Down