IvanRublev / Nestru

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Error when decoding empty lists from maps

alejgh opened this issue · comments

Hi, thanks for your work on this library. I have been using Nestru for a while to decode maps from JSON data into Elixir structs. In the last version of Nestru (0.3.2) the library is returning an error when decoding a map that has an empty list.

Environment

  • Elixir version (elixir -v): 1.14.3
  • Nestru version (mix deps | grep nestru | head -1): 0.3.2

Actual behavior

Supposing we have defined the following structs:

defmodule Order do
  @derive {Nestru.Decoder, hint: %{items: [LineItem]}}

  defstruct [:id, :items]
end

defmodule LineItem do
  @derive Nestru.Decoder
  defstruct [:amount]
end

If we provide a list with LineItem values for the items field, everything works as expected:

map = %{
  "id" => "A548",
  "items" => [%{"amount" => 150}, %{"amount" => 350}]
}

{:ok, model} = Nestru.decode_from_map(map, Order)
{:ok, %Order{id: "A548", items: [%LineItem{amount: 150}, %LineItem{amount: 350}]}}

However, if we provide an empty list for the items field, an error is raised:

map = %{
  "id" => "A548",
  "items" => [],
}

{:ok, model} = Nestru.decode_from_map(map, Order)
{:error,  %{ get_in_keys: [#Function<8.75249601/3 in Access.key!/1>], message: %{message: "The first argument should be a list. Got [] instead."}, path: ["items"]}}

Expected behavior

The map should be decoded correctly, creating an Order struct with an empty list in the items field:

{:ok, %Order{id: "A548", items: []}}

Additional notes

This new error when providing empty lists appeared in version 0.3.2 of Nestru. In version 0.3.1, the expected behavior shown above occurs instead.

Hey @alejgh,
Thanks for noticing! The regression bug is fixed, please, give a try to version 0.3.3.

Hey @alejgh, Thanks for noticing! The regression bug is fixed, please, give a try to version 0.3.3.

I have just tried version 0.3.3 and it seems to work perfectly now. Thank you for the fix! 😄