| 1 |
|
-module(shurbej_http_groups). |
| 2 |
|
-include_lib("shurbej_store/include/shurbej_records.hrl"). |
| 3 |
|
|
| 4 |
|
-export([init/2]). |
| 5 |
|
|
| 6 |
|
init(Req0, State) -> |
| 7 |
7 |
case cowboy_req:method(Req0) of |
| 8 |
|
<<"GET">> -> |
| 9 |
6 |
case shurbej_http_common:authorize(Req0) of |
| 10 |
5 |
{ok, {user, UserId}, _} -> handle_get(UserId, Req0, State); |
| 11 |
|
{error, Reason, _} -> |
| 12 |
1 |
Req = shurbej_http_common:auth_error_response(Reason, Req0), |
| 13 |
1 |
{ok, Req, State} |
| 14 |
|
end; |
| 15 |
|
_ -> |
| 16 |
1 |
Req = shurbej_http_common:error_response(405, <<"Method not allowed">>, Req0), |
| 17 |
1 |
{ok, Req, State} |
| 18 |
|
end. |
| 19 |
|
|
| 20 |
|
%% GET /users/:user_id/groups — list groups the user is a member of. |
| 21 |
|
handle_get(UserId, Req0, State) -> |
| 22 |
5 |
Memberships = shurbej_db:list_user_groups(UserId), |
| 23 |
5 |
Groups = lists:filtermap(fun(#shurbej_group_member{id = {GroupId, _}}) -> |
| 24 |
2 |
case shurbej_db:get_group(GroupId) of |
| 25 |
2 |
{ok, Group} -> {true, Group}; |
| 26 |
:-( |
undefined -> false |
| 27 |
|
end |
| 28 |
|
end, Memberships), |
| 29 |
5 |
Format = shurbej_http_common:get_format(Req0), |
| 30 |
5 |
case Format of |
| 31 |
|
<<"versions">> -> |
| 32 |
2 |
Map = maps:from_list( |
| 33 |
1 |
[{integer_to_binary(G#shurbej_group.group_id), G#shurbej_group.version} |
| 34 |
2 |
|| G <- Groups]), |
| 35 |
2 |
Req = shurbej_http_common:json_response(200, Map, 0, Req0), |
| 36 |
2 |
{ok, Req, State}; |
| 37 |
|
_ -> |
| 38 |
3 |
Body = [shurbej_http_common:envelope_group(G) || G <- Groups], |
| 39 |
3 |
Req = shurbej_http_common:json_response(200, Body, 0, Req0), |
| 40 |
3 |
{ok, Req, State} |
| 41 |
|
end. |