snapkitty
developer-tools
c++
SNAPKITTYWEST commited on
Commit
50738f4
·
verified ·
1 Parent(s): a6b5e84

Add src/hk_api_messages_h.erl

Browse files
Files changed (1) hide show
  1. src/hk_api_messages_h.erl +40 -0
src/hk_api_messages_h.erl ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ %%%-------------------------------------------------------------------
2
+ %%% @doc `/messages' API domain.
3
+ %%%
4
+ %%% POST /api/messages?conversation_id=... send a message
5
+ %%% GET /api/messages?conversation_id=... list that conversation's history
6
+ %%% @end
7
+ %%%-------------------------------------------------------------------
8
+ -module(hk_api_messages_h).
9
+
10
+ -export([init/2]).
11
+
12
+ init(Req0 = #{method := <<"POST">>}, State) ->
13
+ RequestId = hk_api_util:request_id(Req0),
14
+ {ok, Body, Req1} = hk_api_util:read_json_body(Req0),
15
+ Sender = maps:get(<<"sender">>, Body, <<"unknown">>),
16
+ Recipient = maps:get(<<"recipient">>, Body, <<"unknown">>),
17
+ ConversationId = maps:get(<<"conversation_id">>, Body, hk_id:new(<<"conv">>)),
18
+ MessageType = binary_to_atom(maps:get(<<"message_type">>, Body, <<"user_to_agent">>), utf8),
19
+ Payload = maps:get(<<"payload">>, Body, #{}),
20
+ Req = hk_api_util:run_operation(message_send, RequestId, fun() ->
21
+ {ok, MessageId} = hk_messaging_portal:send(Sender, Recipient, ConversationId,
22
+ MessageType, Payload),
23
+ {ok, {message, MessageId}, #{message_id => MessageId, conversation_id => ConversationId}}
24
+ end, Req1),
25
+ {ok, Req, State};
26
+
27
+ init(Req0 = #{method := <<"GET">>}, State) ->
28
+ Qs = cowboy_req:parse_qs(Req0),
29
+ Req = case lists:keyfind(<<"conversation_id">>, 1, Qs) of
30
+ {<<"conversation_id">>, ConversationId} ->
31
+ Messages = hk_messaging_portal:list_conversation(ConversationId),
32
+ hk_api_util:reply_json(200, #{messages => Messages}, Req0);
33
+ false ->
34
+ hk_api_util:reply_error(400, missing_conversation_id, Req0)
35
+ end,
36
+ {ok, Req, State};
37
+
38
+ init(Req0, State) ->
39
+ Req = hk_api_util:reply_error(405, method_not_allowed, Req0),
40
+ {ok, Req, State}.