From 75bca45b9053255b4c4342c902582f1a150ec9d2 Mon Sep 17 00:00:00 2001 From: fishtreesugar Date: Mon, 4 Mar 2024 16:00:01 -0600 Subject: [PATCH] fix: return error when embeds_many field input with wrong type fixes https://github.com/bitwalker/strukt/issues/18 --- lib/params.ex | 7 +++++-- lib/strukt.ex | 2 +- test/strukt_test.exs | 13 +++++++++++++ 3 files changed, 19 insertions(+), 3 deletions(-) diff --git a/lib/params.ex b/lib/params.ex index 3012c7a..e1bfbb5 100644 --- a/lib/params.ex +++ b/lib/params.ex @@ -30,13 +30,13 @@ defmodule Strukt.Params do transform(module, params, struct) end - defp transform(module, params, nil = struct, cardinality: :many) do + defp transform(module, params, nil = struct, cardinality: :many) when is_list(params) do Enum.map(params, fn param -> transform(module, param, struct) end) end - defp transform(module, params, struct, cardinality: :many) do + defp transform(module, params, struct, cardinality: :many) when is_list(params) do params |> Enum.with_index() |> Enum.map(fn {param, index} -> @@ -44,6 +44,9 @@ defmodule Strukt.Params do end) end + # for delay the type error to casting + defp transform(_module, params, _struct, cardinality: :many), do: params + defp transform_from_struct(module, params, struct) do struct |> Map.from_struct() diff --git a/lib/strukt.ex b/lib/strukt.ex index 5d92d04..7538e19 100644 --- a/lib/strukt.ex +++ b/lib/strukt.ex @@ -565,7 +565,7 @@ defmodule Strukt do # When we have a list of entities, we are overwriting the embeds with a new set Ecto.Changeset.put_embed(changeset, field, Enum.map(entities, &Map.from_struct/1)) - other when is_map(other) or is_list(other) -> + other -> # For all other parameters, we need to cast. Depending on how the embedded entity is configured, this may raise an error cast_embed(changeset, field) end diff --git a/test/strukt_test.exs b/test/strukt_test.exs index a624f94..02c66a6 100644 --- a/test/strukt_test.exs +++ b/test/strukt_test.exs @@ -295,6 +295,19 @@ defmodule Strukt.Test do refute is_nil(uuid) end + test "return error when passing wrong typed value to embeds_many field" do + {:error, + %Ecto.Changeset{ + action: :insert, + changes: %{}, + errors: [items: {"is invalid", [validation: :embed, type: {:array, :map}]}], + valid?: false + }} = + Fixtures.CustomFieldsWithEmbeddedSchema.new(%{ + items: "iterms" + }) + end + test "parse custom fields with boolean value" do assert {:ok, %Strukt.Test.Fixtures.CustomFieldsWithBoolean{enabled: false, uuid: uuid}} = Fixtures.CustomFieldsWithBoolean.new(%{Enabled: false})