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