1 |
|
-module(mongoose_graphql_scalar). |
2 |
|
-export([input/2, output/2]). |
3 |
|
-ignore_xref([input/2, output/2]). |
4 |
|
|
5 |
|
-spec input(Type, Value) -> {ok, Coerced} | {error, Reason} |
6 |
|
when |
7 |
|
Type :: binary(), |
8 |
|
Value :: binary(), |
9 |
|
Coerced :: any(), |
10 |
|
Reason :: term(). |
11 |
:-( |
input(<<"DateTime">>, DT) -> binary_to_microseconds(DT); |
12 |
6 |
input(<<"Stanza">>, Value) -> exml:parse(Value); |
13 |
235 |
input(<<"JID">>, Jid) -> jid_from_binary(Jid); |
14 |
8 |
input(<<"NonEmptyString">>, Value) -> non_empty_string_to_binary(Value); |
15 |
|
input(Ty, V) -> |
16 |
:-( |
error_logger:info_report({coercing_generic_scalar, Ty, V}), |
17 |
:-( |
{ok, V}. |
18 |
|
|
19 |
|
-spec output(Type, Value) -> {ok, Coerced} | {error, Reason} |
20 |
|
when |
21 |
|
Type :: binary(), |
22 |
|
Value :: binary(), |
23 |
|
Coerced :: any(), |
24 |
|
Reason :: term(). |
25 |
:-( |
output(<<"DateTime">>, DT) -> {ok, microseconds_to_binary(DT)}; |
26 |
:-( |
output(<<"Stanza">>, Elem) -> {ok, exml:to_binary(Elem)}; |
27 |
53 |
output(<<"JID">>, Jid) -> {ok, jid:to_binary(Jid)}; |
28 |
:-( |
output(<<"NonEmptyString">>, Value) -> binary_to_non_empty_string(Value); |
29 |
|
output(Ty, V) -> |
30 |
:-( |
error_logger:info_report({output_generic_scalar, Ty, V}), |
31 |
:-( |
{ok, V}. |
32 |
|
|
33 |
|
jid_from_binary(Value) -> |
34 |
235 |
case jid:from_binary(Value) of |
35 |
|
error -> |
36 |
1 |
{error, failed_to_parse_jid}; |
37 |
|
Jid -> |
38 |
234 |
{ok, Jid} |
39 |
|
end. |
40 |
|
|
41 |
|
binary_to_microseconds(DT) -> |
42 |
:-( |
case mod_mam_utils:maybe_microseconds(DT) of |
43 |
|
undefined -> |
44 |
:-( |
{error, failed_to_parse_datetime}; |
45 |
|
Microseconds -> |
46 |
:-( |
{ok, Microseconds} |
47 |
|
end. |
48 |
|
|
49 |
|
non_empty_string_to_binary(<<>>) -> |
50 |
2 |
{error, "Given string is empty"}; |
51 |
|
non_empty_string_to_binary(String) -> |
52 |
6 |
{ok, String}. |
53 |
|
|
54 |
|
binary_to_non_empty_string(<<>>) -> |
55 |
:-( |
{error, "Empty binary cannot be converted to NonEmptyString"}; |
56 |
|
binary_to_non_empty_string(Val) -> |
57 |
:-( |
{ok, Val}. |
58 |
|
|
59 |
|
microseconds_to_binary(Microseconds) -> |
60 |
:-( |
Opts = [{offset, "Z"}, {unit, microsecond}], |
61 |
:-( |
list_to_binary(calendar:system_time_to_rfc3339(Microseconds, Opts)). |