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

don't fetch relationships twice #273

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 7 additions & 3 deletions lib/ja_serializer/builder/included.ex
Expand Up @@ -41,16 +41,20 @@ defmodule JaSerializer.Builder.Included do
end

defp resource_objects_for(structs, conn, serializer, opts) do
structs = Enum.filter(structs, &is_map/1)
%{data: structs, conn: conn, serializer: serializer, opts: opts}
|> ResourceObject.build()
|> List.wrap()
end

# Find relationships that should be included.
defp relationships_with_include(context) do
context.data
|> context.serializer.relationships(context.conn)
|> Enum.filter(fn {rel_name, rel_definition} ->
context
|> case do
%{relationships: relationships} -> relationships
%{data: data} -> context.serializer.relationships(data, context.conn)
end
|> Enum.filter(fn({rel_name, rel_definition}) ->
case context[:opts][:include] do
# if `include` param is not present only return 'default' includes
nil ->
Expand Down
9 changes: 9 additions & 0 deletions test/ja_serializer/builder/included_test.exs
Expand Up @@ -477,4 +477,13 @@ defmodule JaSerializer.Builder.IncludedTest do
ids = Enum.map(json["included"], &Map.get(&1, "id"))
assert "p1" in ids
end

test "non-existent include that is serialized into resource identifier results in no includes being added" do
a1 = %TestModel.Article{id: "a1", title: "a1", author: "p1"}

json = JaSerializer.format(ArticleSerializer, a1, %{}, include: "author")
keys = Map.keys(json)
assert not "included" in keys
assert json["data"]["relationships"]["author"]["data"]["id"] == "p1"
end
end