Skip to content

Commit

Permalink
Add the possibility to decode lists of items with deftype (#601)
Browse files Browse the repository at this point in the history
  • Loading branch information
dottorblaster authored May 26, 2022
1 parent d29b14d commit 0f9a73a
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
13 changes: 13 additions & 0 deletions lib/trento/support/type.ex
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,19 @@ defmodule Trento.Type do
def cast_and_validate_required_embed(changeset, field, required_fields),
do: cast_embed(changeset, field, required: field in required_fields)

def from_list(list_of_structs) do
list_of_structs
|> Enum.map(fn item -> __MODULE__.new(item) end)
|> Enum.group_by(
fn {is_valid, _} -> is_valid end,
fn {_, decoding_value} -> decoding_value end
)
|> decoding_results()
end

defp decoding_results(%{error: decoding_errors}), do: {:error, decoding_errors}
defp decoding_results(%{ok: decoding_results}), do: {:ok, decoding_results}

defp fields, do: __MODULE__.__schema__(:fields) -- __MODULE__.__schema__(:embeds)

defp embedded_fields, do: __MODULE__.__schema__(:embeds)
Expand Down
52 changes: 52 additions & 0 deletions test/trento/support/type_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,56 @@ defmodule Trento.TypeTest do
name: "a"
})
end

test "should validate a list of maps" do
assert {:error, [%{embedded: ["can't be blank"]}, %{embedded: ["can't be blank"]}]} ==
TestData.from_list([
%{id: Faker.UUID.v4(), name: "carbonara"},
%{id: Faker.UUID.v4(), name: "amatriciana"}
])

assert {:error, [%{embedded: ["can't be blank"]}, %{embedded: ["can't be blank"]}]} ==
TestData.from_list([
%{id: Faker.UUID.v4(), name: "carbonara"},
%{id: Faker.UUID.v4(), name: "amatriciana"},
%{
id: Faker.UUID.v4(),
name: "cacio_pepe",
embedded: %{id: Faker.UUID.v4(), name: "yay"}
}
])

{
:ok,
[
%TestData{
embedded: %EmbeddedTestData{id: _id1, name: "yay"},
id: _id2,
name: "cacio_pepe"
},
%TestData{
embedded: %EmbeddedTestData{
id: _id3,
name: "wow"
},
id: _id4,
name: "lasagne"
}
] = decoded_list
} =
TestData.from_list([
%{
id: Faker.UUID.v4(),
name: "cacio_pepe",
embedded: %{id: Faker.UUID.v4(), name: "yay"}
},
%{
id: Faker.UUID.v4(),
name: "lasagne",
embedded: %{id: Faker.UUID.v4(), name: "wow"}
}
])

assert 2 == length(decoded_list)
end
end

0 comments on commit 0f9a73a

Please sign in to comment.