1 |
|
-module(mongoose_graphql_response). |
2 |
|
|
3 |
|
-export([term_to_json/1, term_to_pretty_json/1]). |
4 |
|
|
5 |
|
term_to_json(Term) -> |
6 |
997 |
jiffy:encode(fixup(Term)). |
7 |
|
|
8 |
|
term_to_pretty_json(Term) -> |
9 |
586 |
jiffy:encode(fixup(Term), [pretty]). |
10 |
|
|
11 |
|
%% Ground types |
12 |
34772 |
fixup(Term) when is_number(Term) -> Term; |
13 |
7706 |
fixup(Term) when is_atom(Term) -> Term; |
14 |
160826 |
fixup(Term) when is_binary(Term) -> Term; |
15 |
|
%% Compound types |
16 |
|
fixup(Term) when is_list(Term) -> |
17 |
28144 |
[fixup(T) || T <- Term]; |
18 |
|
fixup(Term) when is_map(Term) -> |
19 |
38068 |
KVs = maps:to_list(Term), |
20 |
38068 |
maps:from_list([{fixup_key(K), fixup(V)} || {K, V} <- KVs]); |
21 |
|
fixup(Term) -> |
22 |
|
%% Every other term is transformed into a binary value |
23 |
14 |
iolist_to_binary( |
24 |
|
io_lib:format("~p", [Term])). |
25 |
|
|
26 |
|
fixup_key(Term) -> |
27 |
93613 |
case fixup(Term) of |
28 |
|
T when is_binary(T) -> |
29 |
88176 |
T; |
30 |
|
T -> |
31 |
5437 |
iolist_to_binary(io_lib:format("~p", [T])) |
32 |
|
end. |