Source

webcandy / src / webmstn_notes_resource.erl

The default branch has multiple heads

Full commit
%% @author sunneach http://bitbuckets.com/sunneach
%% @copyright 2009 sunneach
%% @doc Example webmachine_resource.

-module(webmstn_notes_resource).
-export([init/1,content_types_provided/2,allowed_methods/2,content_types_accepted/2,process_post/2]).
-export([to_json/2,from_json/2]).


-include_lib("webmachine/include/webmachine.hrl").

init([]) -> {ok, undefined};
init([Cfg]) -> 
    {trace_dir,Dir} = Cfg,
	AbsDir =filename:absname(Dir), 
	io:format("= = = = = = ~nnotes_resource Cfg=~p,  absdir=~p~n",[Cfg,AbsDir]),
	{{trace,AbsDir}, Cfg}.

content_types_provided(RD,Ctx) ->
    {[{"application/json",to_json}],RD,Ctx}.

to_json(RD, Result) ->
    io:format("--> to_json~n"),
    {mochijson:encode(Result), RD, Result}.

allowed_methods(RD, Ctx) ->
    {['POST'], RD, Ctx}.
%    {['GET', 'HEAD', 'PUT'], RD, Ctx}.

content_types_accepted(RD, Ctx) ->  % called when 'PUT' comes
    io:format("--> content_types_accepted ~p~n",[RD]),
       {[{"application/x-www-form-urlencoded; charset=utf8", from_json}], RD, Ctx}.
%   {[{"application/json", from_json}], RD, Ctx}.
from_json(RD, Ctx) ->
    io:format("--> from_json~n"),
    {true, RD, Ctx}.

process_post(RD,Ctx) ->
%   io:format("--> process_post~n"),
    Data = mochiweb_util:parse_qs(wrq:req_body(RD)),
    io:format("--> process_post Data:~n~p~n",[Data]),
    Struct = mochijson2:decode(proplists:get_value("json", Data)),
%    io:format("--> process_post Struct:~n~p~n",[Struct]),
    Act = list_to_atom(binary_to_list(struct:get_value(<<"action">>, Struct))),
%    io:format("--> process_post Act:~n~p~n",[Act]),
    RD1 = wrq:set_resp_header("Content-Type", "application/json",RD),
    Ans = mochijson2:encode(notes:Act(Struct)),
    io:format("--> process_post DB Response:~p~n",[Ans]),
%    io:format("--> process_post DB Response:~p~nbefore~n~p~n",[Ans,RD]),
    RD2 = wrq:append_to_resp_body(Ans,RD1),
%    RD1 = wrq:append_to_response_body(<<"body here">>,RD1),
%    io:format("--> process_post RD~n~p~n",[RD2]),
    {true,RD2,Ctx}.