-module(nine_cowboy_mid).
-export([
json_request/1,
urlencoded_params/1
]).
json_request(#{req := Req} = Context) ->
case cowboy_req:header(<<"content-type">>, Req) of
<<"application/json", _/binary>> ->
case cowboy_req:read_body(Req) of
{ok, Data, Req1} ->
case thoas:decode(Data) of
{ok, Json} ->
Context#{json => Json, req => Req1};
_ ->
Context#{resp => error_response(Req1, 500, <<"Error decoding JSON">>)}
end;
_ ->
Context#{resp => error_response(Req, 500, <<"Error reading request body">>)}
end;
_ ->
Context#{resp => error_response(Req, 400, <<"Expected JSON">>)}
end.
urlencoded_params(#{req := Req0, params := Params} = Context) ->
case cowboy_req:header(<<"content-type">>, Req0) of
<<"application/x-www-form-urlencoded">> ->
case cowboy_req:read_urlencoded_body(Req0) of
{ok, Body, Req} ->
NewParams = maps:from_list(Body),
Context#{req => Req, params => maps:merge(Params, NewParams)};
_ ->
Context#{resp => error_response(Req0, 500, <<"Error Decoding Params">>)}
end;
_ ->
Context
end.
error_response(Req, ErrorCode, ErrorMessage) ->
cowboy_req:reply(ErrorCode, #{}, ErrorMessage, Req).