From 38ed6f40017a104077b614a14c32ac4e257b6f55 Mon Sep 17 00:00:00 2001 From: Paul Swartz Date: Mon, 2 Apr 2018 11:49:15 -0400 Subject: [PATCH] don't fetch relationships twice For some implementations of `relationships/2`, it can be expensive to calculate. For the top level, we've already calculated the relationships as a part of the `%ResourceObject{}` so we don't need to do it again. --- lib/ja_serializer/builder/included.ex | 8 ++++++-- test/ja_serializer/builder/included_test.exs | 9 +++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/lib/ja_serializer/builder/included.ex b/lib/ja_serializer/builder/included.ex index 75d1ef9..dcca6cc 100644 --- a/lib/ja_serializer/builder/included.ex +++ b/lib/ja_serializer/builder/included.ex @@ -36,6 +36,7 @@ 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 @@ -43,8 +44,11 @@ defmodule JaSerializer.Builder.Included do # Find relationships that should be included. defp relationships_with_include(context) do - context.data - |> context.serializer.relationships(context.conn) + 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 diff --git a/test/ja_serializer/builder/included_test.exs b/test/ja_serializer/builder/included_test.exs index cfa2de3..0ce66c3 100644 --- a/test/ja_serializer/builder/included_test.exs +++ b/test/ja_serializer/builder/included_test.exs @@ -315,4 +315,13 @@ defmodule JaSerializer.Builder.IncludedTest do ids = Enum.map(json["included"], &(Map.get(&1, "id"))) assert not "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