Рефакторинг обработчиков. Часть 2 #21
This commit is contained in:
@@ -1,42 +1,175 @@
|
||||
%%%-------------------------------------------------------------------
|
||||
%%% @doc Обработчик конкретного события (клиентский API).
|
||||
%%%
|
||||
%%% GET – получить информацию о событии.
|
||||
%%% PUT – обновить событие.
|
||||
%%% DELETE – удалить событие.
|
||||
%%% @end
|
||||
%%%-------------------------------------------------------------------
|
||||
-module(handler_event_by_id).
|
||||
-include("records.hrl").
|
||||
-behaviour(cowboy_handler).
|
||||
|
||||
-export([init/2]).
|
||||
-export([trails/0]).
|
||||
|
||||
-include("records.hrl").
|
||||
|
||||
%%% cowboy_handler callback
|
||||
-spec init(cowboy_req:req(), any()) -> {ok, cowboy_req:req(), any()}.
|
||||
init(Req, Opts) ->
|
||||
handle(Req, Opts).
|
||||
|
||||
%%% Swagger metadata
|
||||
-spec trails() -> [map()].
|
||||
trails() ->
|
||||
BaseParams = [
|
||||
#{
|
||||
name => <<"id">>,
|
||||
in => <<"path">>,
|
||||
description => <<"Event ID">>,
|
||||
required => true,
|
||||
schema => #{type => string}
|
||||
}
|
||||
],
|
||||
[
|
||||
#{ % GET by id
|
||||
path => <<"/v1/events/:id">>,
|
||||
method => <<"GET">>,
|
||||
description => <<"Get event by ID">>,
|
||||
tags => [<<"Events">>],
|
||||
parameters => BaseParams,
|
||||
responses => #{
|
||||
200 => #{
|
||||
description => <<"Event details">>,
|
||||
content => #{<<"application/json">> => #{schema => event_schema()}}
|
||||
},
|
||||
403 => #{description => <<"Access denied">>},
|
||||
404 => #{description => <<"Event not found">>}
|
||||
}
|
||||
},
|
||||
#{ % PUT update
|
||||
path => <<"/v1/events/:id">>,
|
||||
method => <<"PUT">>,
|
||||
description => <<"Update event">>,
|
||||
tags => [<<"Events">>],
|
||||
parameters => BaseParams,
|
||||
requestBody => #{
|
||||
required => true,
|
||||
content => #{<<"application/json">> => #{schema => event_update_schema()}}
|
||||
},
|
||||
responses => #{
|
||||
200 => #{description => <<"Event updated">>},
|
||||
400 => #{description => <<"Invalid request">>},
|
||||
403 => #{description => <<"Access denied">>},
|
||||
404 => #{description => <<"Event not found">>}
|
||||
}
|
||||
},
|
||||
#{ % DELETE
|
||||
path => <<"/v1/events/:id">>,
|
||||
method => <<"DELETE">>,
|
||||
description => <<"Delete event">>,
|
||||
tags => [<<"Events">>],
|
||||
parameters => BaseParams,
|
||||
responses => #{
|
||||
200 => #{description => <<"Event deleted">>},
|
||||
403 => #{description => <<"Access denied">>},
|
||||
404 => #{description => <<"Event not found">>}
|
||||
}
|
||||
}
|
||||
].
|
||||
|
||||
event_schema() ->
|
||||
#{
|
||||
type => object,
|
||||
properties => #{
|
||||
id => #{type => string},
|
||||
calendar_id => #{type => string},
|
||||
title => #{type => string},
|
||||
description => #{type => string},
|
||||
event_type => #{type => string, enum => [<<"single">>, <<"recurring">>]},
|
||||
start_time => #{type => string, format => <<"date-time">>},
|
||||
duration => #{type => integer},
|
||||
recurrence => #{type => object, nullable => true},
|
||||
master_id => #{type => string, nullable => true},
|
||||
is_instance => #{type => boolean},
|
||||
specialist_id => #{type => string, nullable => true},
|
||||
location => #{type => object, nullable => true},
|
||||
tags => #{type => array, items => #{type => string}},
|
||||
capacity => #{type => integer, nullable => true},
|
||||
online_link => #{type => string, nullable => true},
|
||||
status => #{type => string, enum => [<<"active">>, <<"cancelled">>, <<"completed">>]},
|
||||
reason => #{type => string, nullable => true},
|
||||
rating_avg => #{type => number, format => float},
|
||||
rating_count => #{type => integer},
|
||||
attachments => #{type => array, items => #{type => string}, nullable => true},
|
||||
edit_history => #{type => array, items => #{type => object}, nullable => true},
|
||||
created_at => #{type => string, format => <<"date-time">>},
|
||||
updated_at => #{type => string, format => <<"date-time">>}
|
||||
}
|
||||
}.
|
||||
|
||||
event_update_schema() ->
|
||||
#{
|
||||
type => object,
|
||||
properties => #{
|
||||
title => #{type => string},
|
||||
description => #{type => string},
|
||||
start_time => #{type => string, format => <<"date-time">>},
|
||||
duration => #{type => integer},
|
||||
status => #{type => string, enum => [<<"active">>, <<"cancelled">>, <<"completed">>]},
|
||||
specialist_id => #{type => string},
|
||||
location => #{
|
||||
type => object,
|
||||
properties => #{
|
||||
address => #{type => string},
|
||||
lat => #{type => number, format => float},
|
||||
lon => #{type => number, format => float}
|
||||
}
|
||||
},
|
||||
tags => #{type => array, items => #{type => string}},
|
||||
capacity => #{type => integer},
|
||||
online_link => #{type => string}
|
||||
}
|
||||
}.
|
||||
|
||||
%%%===================================================================
|
||||
%%% HTTP-методы
|
||||
%%%===================================================================
|
||||
|
||||
%% @private
|
||||
-spec handle(cowboy_req:req(), any()) -> {ok, cowboy_req:req(), any()}.
|
||||
handle(Req, _Opts) ->
|
||||
case cowboy_req:method(Req) of
|
||||
<<"GET">> -> get_event(Req);
|
||||
<<"PUT">> -> update_event(Req);
|
||||
<<"GET">> -> get_event(Req);
|
||||
<<"PUT">> -> update_event(Req);
|
||||
<<"DELETE">> -> delete_event(Req);
|
||||
_ -> send_error(Req, 405, <<"Method not allowed">>)
|
||||
_ -> handler_utils:send_error(Req, 405, <<"Method not allowed">>)
|
||||
end.
|
||||
|
||||
%% GET /v1/events/:id - получение события
|
||||
%% @doc GET /v1/events/:id — получение события.
|
||||
-spec get_event(cowboy_req:req()) -> {ok, binary(), cowboy_req:req()}.
|
||||
get_event(Req) ->
|
||||
case handler_auth:authenticate(Req) of
|
||||
case handler_utils:auth_user(Req) of
|
||||
{ok, UserId, Req1} ->
|
||||
EventId = cowboy_req:binding(id, Req1),
|
||||
case logic_event:get_event(UserId, EventId) of
|
||||
{ok, Event} ->
|
||||
Response = event_to_json(Event),
|
||||
send_json(Req1, 200, Response);
|
||||
handler_utils:send_json(Req1, 200, handler_utils:event_to_json(Event));
|
||||
{error, access_denied} ->
|
||||
send_error(Req1, 403, <<"Access denied">>);
|
||||
handler_utils:send_error(Req1, 403, <<"Access denied">>);
|
||||
{error, not_found} ->
|
||||
send_error(Req1, 404, <<"Event not found">>);
|
||||
handler_utils:send_error(Req1, 404, <<"Event not found">>);
|
||||
{error, _} ->
|
||||
send_error(Req1, 500, <<"Internal server error">>)
|
||||
handler_utils:send_error(Req1, 500, <<"Internal server error">>)
|
||||
end;
|
||||
{error, Code, Message, Req1} ->
|
||||
send_error(Req1, Code, Message)
|
||||
handler_utils:send_error(Req1, Code, Message)
|
||||
end.
|
||||
|
||||
%% PUT /v1/events/:id - обновление события
|
||||
%% @doc PUT /v1/events/:id — обновление события.
|
||||
-spec update_event(cowboy_req:req()) -> {ok, binary(), cowboy_req:req()}.
|
||||
update_event(Req) ->
|
||||
case handler_auth:authenticate(Req) of
|
||||
case handler_utils:auth_user(Req) of
|
||||
{ok, UserId, Req1} ->
|
||||
EventId = cowboy_req:binding(id, Req1),
|
||||
{ok, Body, Req2} = cowboy_req:read_body(Req1),
|
||||
@@ -46,136 +179,83 @@ update_event(Req) ->
|
||||
UpdatesWithTypes = convert_fields(Updates),
|
||||
case logic_event:update_event(UserId, EventId, UpdatesWithTypes) of
|
||||
{ok, Event} ->
|
||||
Response = event_to_json(Event),
|
||||
send_json(Req2, 200, Response);
|
||||
handler_utils:send_json(Req2, 200, handler_utils:event_to_json(Event));
|
||||
{error, access_denied} ->
|
||||
send_error(Req2, 403, <<"Access denied">>);
|
||||
handler_utils:send_error(Req2, 403, <<"Access denied">>);
|
||||
{error, not_found} ->
|
||||
send_error(Req2, 404, <<"Event not found">>);
|
||||
handler_utils:send_error(Req2, 404, <<"Event not found">>);
|
||||
{error, event_in_past} ->
|
||||
send_error(Req2, 400, <<"Event cannot be in the past">>);
|
||||
handler_utils:send_error(Req2, 400, <<"Event cannot be in the past">>);
|
||||
{error, _} ->
|
||||
send_error(Req2, 500, <<"Internal server error">>)
|
||||
handler_utils:send_error(Req2, 500, <<"Internal server error">>)
|
||||
end;
|
||||
_ ->
|
||||
send_error(Req2, 400, <<"Invalid JSON">>)
|
||||
handler_utils:send_error(Req2, 400, <<"Invalid JSON">>)
|
||||
catch
|
||||
_:_ ->
|
||||
send_error(Req2, 400, <<"Invalid JSON format">>)
|
||||
_:_ -> handler_utils:send_error(Req2, 400, <<"Invalid JSON format">>)
|
||||
end;
|
||||
{error, Code, Message, Req1} ->
|
||||
send_error(Req1, Code, Message)
|
||||
handler_utils:send_error(Req1, Code, Message)
|
||||
end.
|
||||
|
||||
%% DELETE /v1/events/:id - удаление события
|
||||
%% @doc DELETE /v1/events/:id — удаление события.
|
||||
-spec delete_event(cowboy_req:req()) -> {ok, binary(), cowboy_req:req()}.
|
||||
delete_event(Req) ->
|
||||
case handler_auth:authenticate(Req) of
|
||||
case handler_utils:auth_user(Req) of
|
||||
{ok, UserId, Req1} ->
|
||||
EventId = cowboy_req:binding(id, Req1),
|
||||
case logic_event:delete_event(UserId, EventId) of
|
||||
{ok, _} ->
|
||||
send_json(Req1, 200, #{status => <<"deleted">>});
|
||||
handler_utils:send_json(Req1, 200, #{status => <<"deleted">>});
|
||||
{error, access_denied} ->
|
||||
send_error(Req1, 403, <<"Access denied">>);
|
||||
handler_utils:send_error(Req1, 403, <<"Access denied">>);
|
||||
{error, not_found} ->
|
||||
send_error(Req1, 404, <<"Event not found">>);
|
||||
handler_utils:send_error(Req1, 404, <<"Event not found">>);
|
||||
{error, _} ->
|
||||
send_error(Req1, 500, <<"Internal server error">>)
|
||||
handler_utils:send_error(Req1, 500, <<"Internal server error">>)
|
||||
end;
|
||||
{error, Code, Message, Req1} ->
|
||||
send_error(Req1, Code, Message)
|
||||
handler_utils:send_error(Req1, Code, Message)
|
||||
end.
|
||||
|
||||
%% Вспомогательные функции
|
||||
%%%===================================================================
|
||||
%%% Вспомогательные функции
|
||||
%%%===================================================================
|
||||
|
||||
%% @private Преобразует поля из бинарных ключей в атомы и значения в правильные типы.
|
||||
-spec convert_fields([{binary(), term()}]) -> [{atom(), term()}].
|
||||
convert_fields(Updates) ->
|
||||
lists:map(fun
|
||||
({start_time, Value}) when is_binary(Value) ->
|
||||
case parse_datetime(Value) of
|
||||
{ok, DateTime} -> {start_time, DateTime};
|
||||
_ -> {start_time, Value}
|
||||
end;
|
||||
({location, Value}) when is_map(Value) ->
|
||||
case Value of
|
||||
#{<<"lat">> := Lat, <<"lon">> := Lon} ->
|
||||
Address = maps:get(<<"address">>, Value, <<"">>),
|
||||
{location, #location{address = Address, lat = Lat, lon = Lon}};
|
||||
_ -> {location, undefined}
|
||||
end;
|
||||
({tags, Value}) when is_list(Value) ->
|
||||
{tags, Value};
|
||||
(Other) -> Other
|
||||
end, Updates).
|
||||
lists:map(fun convert_field/1, Updates).
|
||||
|
||||
parse_datetime(Str) ->
|
||||
try
|
||||
[DateStr, TimeStr] = string:split(Str, "T"),
|
||||
TimeStrNoZ = string:trim(TimeStr, trailing, "Z"),
|
||||
|
||||
[YearStr, MonthStr, DayStr] = string:split(DateStr, "-", all),
|
||||
[HourStr, MinuteStr, SecondStr] = string:split(TimeStrNoZ, ":", all),
|
||||
|
||||
Year = binary_to_integer(YearStr),
|
||||
Month = binary_to_integer(MonthStr),
|
||||
Day = binary_to_integer(DayStr),
|
||||
Hour = binary_to_integer(HourStr),
|
||||
Minute = binary_to_integer(MinuteStr),
|
||||
Second = binary_to_integer(SecondStr),
|
||||
|
||||
{ok, {{Year, Month, Day}, {Hour, Minute, Second}}}
|
||||
-spec convert_field({binary(), term()}) -> {atom(), term()}.
|
||||
convert_field({<<"title">>, Val}) -> {title, Val};
|
||||
convert_field({<<"description">>, Val}) -> {description, Val};
|
||||
convert_field({<<"event_type">>, Val}) -> {event_type, Val};
|
||||
convert_field({<<"start_time">>, Val}) ->
|
||||
case handler_utils:parse_datetime(Val) of
|
||||
{ok, Dt} -> {start_time, Dt};
|
||||
_ -> {start_time, Val}
|
||||
end;
|
||||
convert_field({<<"duration">>, Val}) -> {duration, Val};
|
||||
convert_field({<<"recurrence">>, Val}) ->
|
||||
RuleJson = jsx:encode(Val),
|
||||
{recurrence_rule, RuleJson};
|
||||
convert_field({<<"specialist_id">>, Val}) -> {specialist_id, Val};
|
||||
convert_field({<<"location">>, Val}) when is_map(Val) ->
|
||||
Loc = #location{
|
||||
address = maps:get(<<"address">>, Val, undefined),
|
||||
lat = maps:get(<<"lat">>, Val, undefined),
|
||||
lon = maps:get(<<"lon">>, Val, undefined)
|
||||
},
|
||||
{location, Loc};
|
||||
convert_field({<<"location">>, Val}) -> {location, Val};
|
||||
convert_field({<<"tags">>, Val}) -> {tags, Val};
|
||||
convert_field({<<"capacity">>, Val}) -> {capacity, Val};
|
||||
convert_field({<<"online_link">>, Val}) -> {online_link, Val};
|
||||
convert_field({<<"status">>, Val}) ->
|
||||
try binary_to_existing_atom(Val, utf8) of
|
||||
Atom -> {status, Atom}
|
||||
catch
|
||||
_:_ -> {error, invalid_format}
|
||||
end.
|
||||
|
||||
event_to_json(Event) ->
|
||||
LocationJson = case Event#event.location of
|
||||
undefined -> null;
|
||||
#location{address = Addr, lat = Lat, lon = Lon} ->
|
||||
#{address => Addr, lat => Lat, lon => Lon}
|
||||
end,
|
||||
|
||||
RecurrenceJson = case Event#event.recurrence_rule of
|
||||
undefined -> null;
|
||||
Rule ->
|
||||
Decoded = jsx:decode(Rule, [return_maps]),
|
||||
case Decoded of
|
||||
Map when is_map(Map) -> Map;
|
||||
{ok, Map} -> Map
|
||||
end
|
||||
end,
|
||||
|
||||
#{
|
||||
id => Event#event.id,
|
||||
calendar_id => Event#event.calendar_id,
|
||||
title => Event#event.title,
|
||||
description => Event#event.description,
|
||||
event_type => Event#event.event_type,
|
||||
start_time => datetime_to_iso8601(Event#event.start_time),
|
||||
duration => Event#event.duration,
|
||||
recurrence => RecurrenceJson,
|
||||
master_id => Event#event.master_id,
|
||||
is_instance => Event#event.is_instance,
|
||||
specialist_id => Event#event.specialist_id,
|
||||
location => LocationJson,
|
||||
tags => Event#event.tags,
|
||||
capacity => Event#event.capacity,
|
||||
online_link => Event#event.online_link,
|
||||
status => Event#event.status,
|
||||
rating_avg => Event#event.rating_avg,
|
||||
rating_count => Event#event.rating_count,
|
||||
created_at => datetime_to_iso8601(Event#event.created_at),
|
||||
updated_at => datetime_to_iso8601(Event#event.updated_at)
|
||||
}.
|
||||
|
||||
datetime_to_iso8601({{Year, Month, Day}, {Hour, Minute, Second}}) ->
|
||||
iolist_to_binary(io_lib:format("~4..0B-~2..0B-~2..0BT~2..0B:~2..0B:~2..0BZ",
|
||||
[Year, Month, Day, Hour, Minute, Second])).
|
||||
|
||||
send_json(Req, Status, Data) ->
|
||||
Body = jsx:encode(Data),
|
||||
cowboy_req:reply(Status, #{<<"content-type">> => <<"application/json">>}, Body, Req),
|
||||
{ok, Body, []}.
|
||||
|
||||
send_error(Req, Status, Message) ->
|
||||
Body = jsx:encode(#{error => Message}),
|
||||
cowboy_req:reply(Status, #{<<"content-type">> => <<"application/json">>}, Body, Req),
|
||||
{ok, Body, []}.
|
||||
error:badarg -> {status, Val}
|
||||
end;
|
||||
convert_field(Other) -> Other.
|
||||
Reference in New Issue
Block a user