|
@@ -5,13 +5,17 @@
|
|
|
to_html/2, to_json/2, content_types_accepted/2, delete_resource/2,
|
|
|
handle_urlencoded_data/2, handle_json_data/2]).
|
|
|
|
|
|
+-ifndef(JSON).
|
|
|
+-define(JSON, (config(rest,json,n2o_json))).
|
|
|
+-endif.
|
|
|
+
|
|
|
init(_, _, _) -> {upgrade, protocol, cowboy_rest}.
|
|
|
|
|
|
rest_init(Req, _Opts) ->
|
|
|
{Resource, Req1} = cowboy_req:binding(resource, Req),
|
|
|
Module = case rest_module(Resource) of {ok, M} -> M; _ -> undefined end,
|
|
|
{Id, Req2} = cowboy_req:binding(id, Req1),
|
|
|
- Req3 = wf:header(<<"Access-Control-Allow-Origin">>, <<"*">>, Req2),
|
|
|
+ Req3 = cowboy_req:set_resp_header(<<"Access-Control-Allow-Origin">>, <<"*">>, Req2),
|
|
|
{ok, Req3, #st{resource_module = Module, resource_id = Id}}.
|
|
|
|
|
|
resource_exists(Req, #st{resource_module = undefined} = State) -> {false, Req, State};
|
|
@@ -42,7 +46,7 @@ to_json(Req, #st{resource_module = M, resource_id = Id} = State) ->
|
|
|
Struct = case Id of
|
|
|
undefined -> {struct, [{M, [{struct, M:to_json(Resource)} || Resource <- M:get()]}]};
|
|
|
_ -> {struct, M:to_json(M:get(Id))} end,
|
|
|
- {iolist_to_binary(n2o_json:encode(Struct)), Req, State}.
|
|
|
+ {iolist_to_binary(?JSON:encode(Struct)), Req, State}.
|
|
|
|
|
|
content_types_accepted(Req, State) -> {[{<<"application/x-www-form-urlencoded">>, handle_urlencoded_data},
|
|
|
{<<"application/json">>, handle_json_data}], Req, State}.
|
|
@@ -53,7 +57,7 @@ handle_urlencoded_data(Req, #st{resource_module = M, resource_id = Id} = State)
|
|
|
|
|
|
handle_json_data(Req, #st{resource_module = M, resource_id = Id} = State) ->
|
|
|
{ok, Binary, Req2} = cowboy_req:body(Req),
|
|
|
- Data = case n2o_json:decode(Binary) of {struct, Struct} -> Struct; _ -> [] end,
|
|
|
+ Data = case ?JSON:decode(Binary) of {struct, Struct} -> Struct; _ -> [] end,
|
|
|
{handle_data(M, Id, Data), Req2, State}.
|
|
|
|
|
|
handle_data(Mod, Id, Data) ->
|
|
@@ -99,3 +103,9 @@ rest_module(Module) ->
|
|
|
true = lists:member(rest, proplists:get_value(behaviour, Info)),
|
|
|
{ok, M}
|
|
|
catch error:Error -> {error, Error} end.
|
|
|
+
|
|
|
+config(Key) -> config(rest, Key, "").
|
|
|
+config(App,Key) -> config(App,Key, "").
|
|
|
+config(App, Key, Default) -> case application:get_env(App,Key) of
|
|
|
+ undefined -> Default;
|
|
|
+ {ok,V} -> V end.
|