./ct_report/coverage/mongoose_admin_api_stanzas.COVER.html

1 -module(mongoose_admin_api_stanzas).
2
3 -behaviour(mongoose_admin_api).
4 -export([routes/1]).
5
6 -behaviour(cowboy_rest).
7 -export([init/2,
8 is_authorized/2,
9 content_types_accepted/2,
10 allowed_methods/2,
11 from_json/2]).
12
13 -ignore_xref([to_json/2, from_json/2]).
14
15 -import(mongoose_admin_api, [parse_body/1, try_handle_request/3, throw_error/2]).
16
17 -type req() :: cowboy_req:req().
18 -type state() :: mongoose_admin_api:state().
19
20 -spec routes(state()) -> mongoose_http_handler:routes().
21 routes(State) ->
22 111 [{"/stanzas", ?MODULE, State}].
23
24 -spec init(req(), state()) -> {cowboy_rest, req(), state()}.
25 init(Req, State) ->
26 9 mongoose_admin_api:init(Req, State).
27
28 -spec is_authorized(req(), state()) -> {true | {false, iodata()}, req(), state()}.
29 is_authorized(Req, State) ->
30 9 mongoose_admin_api:is_authorized(Req, State).
31
32 -spec content_types_accepted(req(), state()) ->
33 {[{{binary(), binary(), '*'}, atom()}], req(), state()}.
34 content_types_accepted(Req, State) ->
35 9 {[
36 {{<<"application">>, <<"json">>, '*'}, from_json}
37 ], Req, State}.
38
39 -spec allowed_methods(req(), state()) -> {[binary()], req(), state()}.
40 allowed_methods(Req, State) ->
41 9 {[<<"OPTIONS">>, <<"POST">>], Req, State}.
42
43 %% @doc Called for a method of type "POST"
44 -spec from_json(req(), state()) -> {true | stop, req(), state()}.
45 from_json(Req, State) ->
46 9 try_handle_request(Req, State, fun handle_post/2).
47
48 %% Internal functions
49
50 handle_post(Req, State) ->
51 9 Args = parse_body(Req),
52 9 Stanza = get_stanza(Args),
53 7 case mongoose_stanza_api:send_stanza(undefined, Stanza) of
54 {ok, _} ->
55 1 {true, Req, State};
56 {_Error, Msg} ->
57 6 throw_error(bad_request, Msg)
58 end.
59
60 get_stanza(#{stanza := BinStanza}) ->
61 8 case exml:parse(BinStanza) of
62 {ok, Stanza} ->
63 7 Stanza;
64 {error, _} ->
65 1 throw_error(bad_request, <<"Malformed stanza">>)
66 end;
67 get_stanza(#{}) ->
68 1 throw_error(bad_request, <<"Missing stanza">>).
Line Hits Source