Skip to content

Commit

Permalink
fix incorrect ordering of serialized lists
Browse files Browse the repository at this point in the history
  • Loading branch information
protestContest authored and mattpolzin committed Aug 21, 2024
1 parent 78ca704 commit d01c956
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 6 deletions.
17 changes: 11 additions & 6 deletions lib/jsonapi/serializer.ex
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,13 @@ defmodule JSONAPI.Serializer do
def encode_data(_view, nil, _conn, _query_includes, _options), do: {[], nil}

def encode_data(view, data, conn, query_includes, options) when is_list(data) do
Enum.map_reduce(data, [], fn d, acc ->
{to_include, encoded_data} = encode_data(view, d, conn, query_includes, options)
{to_include, Enum.reverse([encoded_data | acc])}
end)
{to_include, encoded_data} =
Enum.map_reduce(data, [], fn d, acc ->
{to_include, encoded_data} = encode_data(view, d, conn, query_includes, options)
{to_include, [encoded_data | acc]}
end)

{to_include, Enum.reverse(encoded_data)}
end

def encode_data(view, data, conn, query_includes, options) do
Expand Down Expand Up @@ -115,9 +118,10 @@ defmodule JSONAPI.Serializer do
query_includes
# credo:disable-for-next-line
|> Enum.reduce([], fn
{^relationship_name, value}, acc -> Enum.reverse([value | acc])
{^relationship_name, value}, acc -> [value | acc]
_, acc -> acc
end)
|> Enum.reverse()
|> List.flatten()
else
[]
Expand All @@ -126,7 +130,8 @@ defmodule JSONAPI.Serializer do
{rel_included, encoded_rel} =
encode_data(rel_view, rel_data, conn, rel_query_includes, options)

{Enum.reverse([encoded_rel | rel_included]), acc}
# credo:disable-for-next-line
{rel_included ++ [encoded_rel], acc}
else
{nil, acc}
end
Expand Down
20 changes: 20 additions & 0 deletions test/jsonapi/serializer_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,26 @@ defmodule JSONAPI.SerializerTest do
assert Enum.count(encoded[:included]) == 4
end

test "serialize keeps the order of a list" do
data1 = %{id: 1}
data2 = %{id: 2}
data3 = %{id: 3}

data_list = [data1, data2, data3]

conn = Plug.Conn.fetch_query_params(%Plug.Conn{})

encoded = Serializer.serialize(PostView, data_list, conn)

assert %{
data: [
%{id: "1"},
%{id: "2"},
%{id: "3"}
]
} = encoded
end

test "serialize handles an empty relationship" do
data = %{
id: 1,
Expand Down

0 comments on commit d01c956

Please sign in to comment.