feat(emqx_message): add from_map
This commit is contained in:
parent
4373367c15
commit
9087f0c138
|
@ -67,8 +67,21 @@
|
|||
-export([ to_packet/2
|
||||
, to_map/1
|
||||
, to_list/1
|
||||
, from_map/1
|
||||
]).
|
||||
|
||||
-export_type([message_map/0]).
|
||||
|
||||
-type(message_map() :: #{id := binary(),
|
||||
qos := 0 | 1 | 2,
|
||||
from := atom() | binary(),
|
||||
flags := emqx_types:flags(),
|
||||
headers := emqx_types:headers(),
|
||||
topic := emqx_types:topic(),
|
||||
payload := emqx_types:payload(),
|
||||
timestamp := integer()}
|
||||
).
|
||||
|
||||
-export([format/1]).
|
||||
|
||||
-spec(make(emqx_topic:topic(), emqx_types:payload()) -> emqx_types:message()).
|
||||
|
@ -266,7 +279,7 @@ filter_pub_props(Props) ->
|
|||
], Props).
|
||||
|
||||
%% @doc Message to map
|
||||
-spec(to_map(emqx_types:message()) -> map()).
|
||||
-spec(to_map(emqx_types:message()) -> message_map()).
|
||||
to_map(#message{
|
||||
id = Id,
|
||||
qos = QoS,
|
||||
|
@ -292,6 +305,28 @@ to_map(#message{
|
|||
to_list(Msg) ->
|
||||
lists:zip(record_info(fields, message), tl(tuple_to_list(Msg))).
|
||||
|
||||
%% @doc Map to message
|
||||
-spec(from_map(message_map()) -> emqx_types:message()).
|
||||
from_map(#{id := Id,
|
||||
qos := QoS,
|
||||
from := From,
|
||||
flags := Flags,
|
||||
headers := Headers,
|
||||
topic := Topic,
|
||||
payload := Payload,
|
||||
timestamp := Timestamp
|
||||
}) ->
|
||||
#message{
|
||||
id = Id,
|
||||
qos = QoS,
|
||||
from = From,
|
||||
flags = Flags,
|
||||
headers = Headers,
|
||||
topic = Topic,
|
||||
payload = Payload,
|
||||
timestamp = Timestamp
|
||||
}.
|
||||
|
||||
%% MilliSeconds
|
||||
elapsed(Since) ->
|
||||
max(0, erlang:system_time(millisecond) - Since).
|
||||
|
|
|
@ -210,3 +210,15 @@ t_to_map(_) ->
|
|||
?assertEqual(List, emqx_message:to_list(Msg)),
|
||||
?assertEqual(maps:from_list(List), emqx_message:to_map(Msg)).
|
||||
|
||||
t_from_map(_) ->
|
||||
Msg = emqx_message:make(<<"clientid">>, ?QOS_1, <<"topic">>, <<"payload">>),
|
||||
Map = #{id => emqx_message:id(Msg),
|
||||
qos => ?QOS_1,
|
||||
from => <<"clientid">>,
|
||||
flags => #{},
|
||||
headers => #{},
|
||||
topic => <<"topic">>,
|
||||
payload => <<"payload">>,
|
||||
timestamp => emqx_message:timestamp(Msg)},
|
||||
?assertEqual(Map, emqx_message:to_map(Msg)),
|
||||
?assertEqual(Msg, emqx_message:from_map(emqx_message:to_map(Msg))).
|
||||
|
|
Loading…
Reference in New Issue