-
Notifications
You must be signed in to change notification settings - Fork 76
Expand file tree
/
Copy pathserializer.ex
More file actions
359 lines (290 loc) · 10.9 KB
/
serializer.ex
File metadata and controls
359 lines (290 loc) · 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
defmodule JSONAPI.Serializer do
@moduledoc """
Serialize a map of data into a properly formatted JSON API response object
"""
require Logger
alias JSONAPI.{Config, Utils, View}
alias Plug.Conn
@type document :: map()
@doc """
Takes a view, data and a optional plug connection and returns a fully JSONAPI Serialized document.
This assumes you are using the JSONAPI.View and have data in maps or structs.
Please refer to `JSONAPI.View` for more information. If you are in interested in relationships
and includes you may also want to reference the `JSONAPI.QueryParser`.
"""
@spec serialize(View.t(), View.data(), Conn.t() | nil, View.meta() | nil, View.options()) ::
document()
def serialize(view, data, conn \\ nil, meta \\ nil, options \\ []) do
{query_includes, query_page} =
case conn do
%Conn{assigns: %{jsonapi_query: %Config{include: include, page: page}}} ->
{include, page}
_ ->
{[], nil}
end
{to_include, encoded_data} = encode_data(view, data, conn, query_includes, options)
encoded_data = %{
data: encoded_data,
included: flatten_included(to_include)
}
encoded_data =
if is_map(meta) do
Map.put(encoded_data, :meta, meta)
else
encoded_data
end
merge_links(encoded_data, data, view, conn, query_page, add_auto_links?(), options, true)
end
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
{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
valid_includes = get_includes(view, query_includes, data)
encoded_data = %{
id: view.id(data),
type: view.resource_type(data),
attributes: transform_fields(view.attributes(data, conn)),
relationships: %{}
}
doc = merge_links(encoded_data, data, view, conn, nil, add_auto_links?(), options, false)
doc =
case view.meta(data, conn) do
nil -> doc
meta -> Map.put(doc, :meta, meta)
end
encode_relationships(conn, doc, {view, data, query_includes, valid_includes}, options)
end
@spec encode_relationships(Conn.t(), document(), tuple(), list()) :: tuple()
def encode_relationships(conn, doc, {view, data, _, _} = view_info, options) do
data
|> view.visible_relationships(conn)
|> Enum.filter(&assoc_loaded?(Map.get(data, get_data_key(&1))))
|> Enum.map_reduce(doc, &build_relationships(conn, view_info, &1, &2, options))
end
defp get_data_key(rel_config), do: elem(extrapolate_relationship_config(rel_config), 1)
@spec build_relationships(Conn.t(), tuple(), term(), term(), module(), tuple(), list()) ::
tuple()
def build_relationships(
conn,
{parent_view, parent_data, query_includes, valid_includes},
relationship_name,
rel_data,
rel_view,
acc,
options
) do
# Build the relationship url
rel_key = transform_fields(relationship_name)
rel_url = parent_view.url_for_rel(parent_data, rel_key, conn)
# Build the relationship
acc =
put_in(
acc,
[:relationships, rel_key],
encode_relation({rel_view, rel_data, rel_url, conn})
)
valid_include_view = include_view(valid_includes, relationship_name)
if {rel_view, :include} == valid_include_view && data_loaded?(rel_data) do
rel_query_includes =
if is_list(query_includes) do
query_includes
# credo:disable-for-next-line
|> Enum.reduce([], fn
{^relationship_name, value}, acc -> [value | acc]
_, acc -> acc
end)
|> Enum.reverse()
|> List.flatten()
else
[]
end
{rel_included, encoded_rel} =
encode_data(rel_view, rel_data, conn, rel_query_includes, options)
# credo:disable-for-next-line
{rel_included ++ [encoded_rel], acc}
else
{nil, acc}
end
end
@spec build_relationships(Conn.t(), tuple(), tuple(), tuple(), list()) :: tuple()
def build_relationships(
conn,
{_parent_view, data, _query_includes, _valid_includes} = parent_info,
rel_config,
acc,
options
) do
{rewrite_key, data_key, rel_view, _include} = extrapolate_relationship_config(rel_config)
rel_data = Map.get(data, data_key)
build_relationships(
conn,
parent_info,
rewrite_key,
rel_data,
rel_view,
acc,
options
)
end
@doc """
Given the relationship config entry provided by a JSONAPI.View, produce
the extrapolated config tuple containing:
- The name of the relationship to be used when serializing
- The key in the data the relationship is found under
- The relationship resource's JSONAPI.View module
- A boolean for whether the relationship is included by default or not
"""
@spec extrapolate_relationship_config(tuple()) :: {atom(), atom(), module(), boolean()}
def extrapolate_relationship_config({rewrite_key, {data_key, view, :include}}) do
{rewrite_key, data_key, view, true}
end
def extrapolate_relationship_config({data_key, {view, :include}}) do
{data_key, data_key, view, true}
end
def extrapolate_relationship_config({rewrite_key, {data_key, view}}) do
{rewrite_key, data_key, view, false}
end
def extrapolate_relationship_config({data_key, view}) do
{data_key, data_key, view, false}
end
defp include_view(valid_includes, key) when is_list(valid_includes) do
valid_includes
|> Keyword.get(key)
|> generate_view_tuple
end
defp include_view(view, _key), do: generate_view_tuple(view)
defp generate_view_tuple({_rewrite_key, view, :include}), do: {view, :include}
defp generate_view_tuple({view, :include}), do: {view, :include}
defp generate_view_tuple({_rewrite_key, view}), do: {view, :include}
defp generate_view_tuple(view) when is_atom(view), do: {view, :include}
@spec data_loaded?(map() | list()) :: boolean()
def data_loaded?(rel_data) do
assoc_loaded?(rel_data) && (is_map(rel_data) || is_list(rel_data))
end
@spec encode_relation(tuple()) :: map()
def encode_relation({rel_view, rel_data, _rel_url, _conn} = info) do
data = %{
data: encode_rel_data(rel_view, rel_data)
}
merge_related_links(data, info, add_auto_links?())
end
defp merge_links(doc, data, view, conn, _page, false, _options, is_root_of_doc) do
merge_view_links(doc, data, view, conn, is_root_of_doc)
end
defp merge_links(doc, data, view, conn, page, true, options, is_root_of_doc) do
doc
|> merge_auto_links(data, view, conn, page, options)
|> merge_view_links(data, view, conn, is_root_of_doc)
end
defp merge_view_links(doc, data, view, conn, is_root_of_doc)
defp merge_view_links(%{links: links} = doc, data, view, conn, false) do
# intentionally take the view.links and merge them into the existing links,
# allowing the custom defined links for the view to override any auto-links
# generated by this library UNLESS configured to remove links (backwards
# compatibility):
view_links =
if remove_links?() do
%{}
else
Map.merge(links, view.links(data, conn))
end
new_doc = Map.merge(doc, %{links: view_links})
case new_doc do
%{links: links} when links == %{} ->
Map.delete(doc, :links)
doc ->
doc
end
end
defp merge_view_links(doc, data, view, conn, false),
do: merge_view_links(Map.merge(doc, %{links: %{}}), data, view, conn, false)
defp merge_view_links(doc, _data, _view, _conn, true), do: doc
defp merge_auto_links(doc, data, view, conn, page, options)
when is_list(data) do
auto_links =
data
|> view.pagination_links(conn, page, options)
|> Map.merge(%{
self: view.url_for_pagination(data, conn, page)
})
Map.merge(doc, %{links: auto_links})
end
defp merge_auto_links(doc, data, view, conn, _page, _options) do
auto_links = %{self: view.url_for(data, conn)}
Map.merge(doc, %{links: auto_links})
end
defp merge_related_links(
encoded_data,
{rel_view, rel_data, rel_url, conn},
true = _add_auto_links
) do
Map.merge(encoded_data, %{links: %{self: rel_url, related: rel_view.url_for(rel_data, conn)}})
end
defp merge_related_links(encoded_rel_data, _info, _add_auto_links), do: encoded_rel_data
@spec encode_rel_data(module(), map() | list()) :: map() | nil
def encode_rel_data(_view, nil), do: nil
def encode_rel_data(view, data) when is_list(data) do
Enum.map(data, &encode_rel_data(view, &1))
end
def encode_rel_data(view, data) do
%{
type: view.resource_type(data),
id: view.id(data)
}
end
# Flatten and unique all the included objects
@spec flatten_included(keyword()) :: keyword()
def flatten_included(included) do
included
|> List.flatten()
|> Enum.reject(&is_nil/1)
|> Enum.uniq()
end
defp assoc_loaded?(nil), do: serialize_nil_relationships?()
defp assoc_loaded?(%{__struct__: Ecto.Association.NotLoaded}), do: false
defp assoc_loaded?(_association), do: true
defp get_includes(view, query_includes, data) do
includes = get_default_includes(view, data) ++ get_query_includes(view, query_includes, data)
Enum.uniq(includes)
end
defp get_default_includes(view, data) do
rels = view.visible_relationships(data, nil)
Enum.filter(rels, &include_rel_by_default/1)
end
defp include_rel_by_default(rel_config) do
{_rel_key, _data_key, _view, include_by_default} = extrapolate_relationship_config(rel_config)
include_by_default
end
defp get_query_includes(view, query_includes, data) do
rels = view.visible_relationships(data, nil)
query_includes
|> Enum.map(fn
{include, _} -> Keyword.take(rels, [include])
include -> Keyword.take(rels, [include])
end)
|> List.flatten()
end
defp remove_links? do
Application.get_env(:jsonapi, :remove_links, false)
end
defp add_auto_links? do
Application.get_env(:jsonapi, :add_auto_links, !remove_links?())
end
@spec serialize_nil_relationships? :: boolean()
defp serialize_nil_relationships?, do: Application.get_env(:jsonapi, :serialize_nil_relationships, false)
defp transform_fields(fields) do
case Utils.String.field_transformation() do
:camelize -> Utils.String.expand_fields(fields, &Utils.String.camelize/1)
:dasherize -> Utils.String.expand_fields(fields, &Utils.String.dasherize/1)
:camelize_shallow -> Utils.String.expand_root_keys(fields, &Utils.String.camelize/1)
:dasherize_shallow -> Utils.String.expand_root_keys(fields, &Utils.String.dasherize/1)
_ -> fields
end
end
end