1 |
|
-module(mongoose_graphql_response). |
2 |
|
|
3 |
|
-export([term_to_json/1, term_to_pretty_json/1]). |
4 |
|
|
5 |
|
term_to_json(Term) -> |
6 |
1003 |
jiffy:encode(fixup(Term)). |
7 |
|
|
8 |
|
term_to_pretty_json(Term) -> |
9 |
599 |
jiffy:encode(fixup(Term), [pretty]). |
10 |
|
|
11 |
|
%% Ground types |
12 |
19649 |
fixup(Term) when is_number(Term) -> Term; |
13 |
7755 |
fixup(Term) when is_atom(Term) -> Term; |
14 |
103679 |
fixup(Term) when is_binary(Term) -> Term; |
15 |
|
%% Compound types |
16 |
|
fixup(Term) when is_list(Term) -> |
17 |
20340 |
[fixup(T) || T <- Term]; |
18 |
|
fixup(Term) when is_map(Term) -> |
19 |
27642 |
KVs = maps:to_list(Term), |
20 |
27642 |
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 |
63277 |
case fixup(Term) of |
28 |
|
T when is_binary(T) -> |
29 |
57794 |
T; |
30 |
|
T -> |
31 |
5483 |
iolist_to_binary(io_lib:format("~p", [T])) |
32 |
|
end. |