Skip to content

Instantly share code, notes, and snippets.

@gumayunov
Created March 3, 2009 11:47
Show Gist options
  • Save gumayunov/73293 to your computer and use it in GitHub Desktop.
Save gumayunov/73293 to your computer and use it in GitHub Desktop.
-module(contacts).
-export([resources/0, filters/0, contacts/4, contacts/3]).
-behaviour(controller).
resources() ->
[
#resources{
path = {users, contacts},
id = int,
formats = [json],
only = [index, show, update, desoroy, create]
},
#resource{
path = {users, contacts, new},
formats = [json],
only = [show]
}
].
filters() -> [].
new( ResourceServer, {show, json}, Request )->
{ok,{struct,[]}}.
contacts( ResourceServer, {show, json}, Id, Request ) ->
User = request:collection_id(Request, users),
Contact = contact_server:get_contact(User,ContactUser),
case Contact of
{G,U} -> {ok,{struct,[{user,U }, {group,G}]}};
_ -> not_found
end.
contacts( ResourceServer, {update, json}, Id, Request ) ->
User = request:collection_id(Request, users),
GroupId = request:int_param(Request, "group_id", 0),
contact_server:add_to_contacts(User,GroupId,ContactUser),
{ok,{struct,[{contact_id,Id}, {group_id,GroupId}]}}.
contacts( ResourceServer, {destroy, json}, Id, Request ) ->
User = request:collection_id(Request, users),
contact_server:remove_from_contacts(User,Id),
{ok,{struct,[{contact_id,Id}, {group_id,null}]}}.
contacts( ResourceServer, {create, json}, Request ) ->
User = request:collection_id(Request, users),
GroupId = request:int_param(Params,"group_id",0),
ContactId = request:int_param(Params,"contact_id", undef),
case ContactId of
undef ->
bad_request;
_ ->
contact_server:add_to_contacts(User,GroupId,ContactUser),
{ok,{struct,[{contact_id,Id}, {group_id,GroupId}]}}
end.
contacts( _ResourceServer, {index, json}, Request ) ->
User = request:collection_id(Request, users),
Contacts = contact_server:get_contacts(User),
{ok,{array,lists:map( fun({G,U}) -> {struct,[{contact_id,U }, {group_id,G}]} end, Contacts) } }.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment