1 |
|
-module(mongoose_graphql_last_helper). |
2 |
|
|
3 |
|
-export([get_last/1, set_last/3]). |
4 |
|
|
5 |
|
-export([microseconds_to_seconds/1, seconds_to_microseconds/1, format_old_users/1]). |
6 |
|
|
7 |
|
-ignore_xref([microseconds_to_seconds/1, seconds_to_microseconds/1]). |
8 |
|
|
9 |
|
-include("mongoose_graphql_types.hrl"). |
10 |
|
|
11 |
|
-import(mongoose_graphql_helper, [make_error/2, null_to_default/2]). |
12 |
|
|
13 |
|
-type old_users() :: [{ok, map()}]. |
14 |
|
-type last_info() :: map(). |
15 |
|
-type timestamp() :: mod_last:timestamp() | null. |
16 |
|
-type status() :: mod_last:status(). |
17 |
|
|
18 |
|
-export_type([last_info/0, old_users/0]). |
19 |
|
|
20 |
|
-spec get_last(jid:jid()) -> {ok, last_info()} | {error, resolver_error()}. |
21 |
|
get_last(JID) -> |
22 |
10 |
case mod_last_api:get_last(JID) of |
23 |
|
{ok, #{timestamp := T, status := S}} -> |
24 |
4 |
{ok, #{<<"user">> => JID, <<"timestamp">> => seconds_to_microseconds(T), |
25 |
|
<<"status">> => S}}; |
26 |
|
Error -> |
27 |
6 |
make_error(Error, #{user => jid:to_binary(JID)}) |
28 |
|
end. |
29 |
|
|
30 |
|
-spec set_last(jid:jid(), timestamp(), status()) -> {ok, last_info()} | {error, resolver_error()}. |
31 |
|
set_last(JID, Timestamp, Status) -> |
32 |
40 |
DefTimestamp = microseconds_to_seconds(null_to_default(Timestamp, os:system_time(microsecond))), |
33 |
40 |
case mod_last_api:set_last(JID, DefTimestamp, Status) of |
34 |
|
{ok, #{timestamp := DefTimestamp, status := Status}} -> |
35 |
36 |
{ok, #{<<"user">> => JID, <<"timestamp">> => seconds_to_microseconds(DefTimestamp), |
36 |
|
<<"status">> => Status}}; |
37 |
|
Error -> |
38 |
4 |
make_error(Error, #{user => jid:to_binary(JID)}) |
39 |
|
end. |
40 |
|
|
41 |
|
format_old_users(OldUsers) -> |
42 |
16 |
[{ok, make_old_user(JID, Timestamp)} || {JID, Timestamp} <- OldUsers]. |
43 |
|
|
44 |
|
microseconds_to_seconds(Timestamp) -> |
45 |
68 |
Timestamp div 1000000. |
46 |
|
|
47 |
|
seconds_to_microseconds(Timestamp) -> |
48 |
52 |
Timestamp * 1000000. |
49 |
|
|
50 |
|
%% Internal |
51 |
|
|
52 |
|
make_old_user(JID, null) -> |
53 |
6 |
#{<<"jid">> => JID, <<"timestamp">> => null}; |
54 |
|
make_old_user(JID, Timestamp) -> |
55 |
12 |
#{<<"jid">> => JID, <<"timestamp">> => seconds_to_microseconds(Timestamp)}. |