Skip to content

Instantly share code, notes, and snippets.

@rokob
Created January 21, 2013 18:42
Show Gist options
  • Save rokob/4588246 to your computer and use it in GitHub Desktop.
Save rokob/4588246 to your computer and use it in GitHub Desktop.
init(_Transport, _Req, _Opts) ->
{upgrade, protocol, cowboy_rest}.
rest_init(Req, _Opts) ->
{ok, Req, #state{}}.
allowed_methods(Req, State=#state{}) ->
{[<<"POST">>], Req, State}.
content_types_accepted(Req, State=#state{}) ->
Types = [
{{<<"application">>, <<"json">>, []}, post_json}
],
{Types, Req, State}.
content_types_provided(Req, State=#state{}) ->
Types = [
{{<<"application">>, <<"json">>, []}, nothing}
],
{Types, Req, State}.
post_is_create(Req, State=#state{}) ->
{true, Req, State}.
create_path(Req, State=#state{}) ->
Key = make_a_key(),
{Path, Req2} = cowboy_req:path(Req),
Path2 = erlang:iolist_to_binary([Path, <<"/">>, Key]),
{Path2, Req2, State#state{key=Key}}.
post_json(Req, State=#state{}) ->
{ok, Body, Req1} = cowboy_req:body(Req),
Json = jiffy:decode(Body),
A = process_json(Json),
{ok, B} = save(A),
Resp = to_json(B),
Req2 = cowboy_req:set_resp_body(B, Req1),
Req3 = cowboy_req:set_resp_header(<<"content-type">>,
<<"application/json">>, Req2),
{true, Req3, State}.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment