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

fix: [#334] Fix incorrect ordering of serialized lists #333

Merged
merged 1 commit into from
Aug 21, 2024
Merged
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
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
Loading