/
utils.ex
52 lines (41 loc) · 1.38 KB
/
utils.ex
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
defmodule JaSerializer.Builder.Utils do
@moduledoc """
Utilities to work with building serialized data
"""
def safe_atom_list(field_str) do
field_str
|> String.split(",")
|> Enum.map(&String.to_existing_atom/1)
end
def normalize_includes(nil), do: []
def normalize_includes(""), do: []
def normalize_includes(includes) do
includes
|> String.split(",")
|> normalize_relationship_path_list
end
defp normalize_relationship_path_list(paths),
do: normalize_relationship_path_list(paths, [])
defp normalize_relationship_path_list([], normalized), do: normalized
defp normalize_relationship_path_list([path | paths], normalized) do
normalized =
path
|> String.split(".")
|> Enum.map(&JaSerializer.ParamParser.Utils.format_key/1)
|> normalize_relationship_path
|> deep_merge_relationship_paths(normalized)
normalize_relationship_path_list(paths, normalized)
end
defp normalize_relationship_path([]), do: []
defp normalize_relationship_path([rel_name | remaining]) do
Keyword.put(
[],
String.to_atom(rel_name),
normalize_relationship_path(remaining)
)
end
defp deep_merge_relationship_paths(left, right),
do: Keyword.merge(left, right, &deep_merge_relationship_paths/3)
defp deep_merge_relationship_paths(_key, left, right),
do: deep_merge_relationship_paths(left, right)
end