Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ferigis.66.add from ctx #67

Merged
merged 4 commits into from
Feb 24, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 43 additions & 33 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,10 @@ to_json(Element) ->
, created_at => sr_json:encode_date(maps:get(created_at, Element))
, updated_at => sr_json:encode_date(maps:get(updated_at, Element))
}.
```

In order to convert from json we have two options: `from_json` or `from_ctx`. The difference is `from_json` accepts only a json body as a parameter, `from_ctx` receive a `context` structure which has the entire request and handler state besides the json body. We will see a `from_ctx` example in `sessions` section
```erlang
-spec from_json(sumo_rest_doc:json()) -> {ok, element()} | {error, iodata()}.
from_json(Json) ->
Now = sr_json:encode_date(calendar:universal_time()),
Expand Down Expand Up @@ -268,7 +271,46 @@ id_from_binding(BinaryId) ->
The rest of the functions in the module are just helpers, particularly useful for our tests.

#### Sessions
[Sessions](test/sr_test/sr_sessions.erl) are very similar to elements. The only difference here is that session ids (unlike element keys) are auto-generated by the mnesia store. Therefore they're initially `undefined`. We don't need to provide a `duplication_conditions/1` function in this case since we don't need to avoid duplicates.
[Sessions](test/sr_test/sr_sessions.erl) are very similar to elements. One difference is that session ids (unlike element keys) are auto-generated by the mnesia store. Therefore they're initially `undefined`. We don't need to provide a `duplication_conditions/1` function in this case since we don't need to avoid duplicates.

The most important difference with elements is sessions does't implement `from_json` callback. Remember, `from_json` only accepts the request body in json format. In sessions we also need the logged user in order to build our session. In this case we implement `from_ctx` instead of `from_json` since it accepts the entire request and the handler's state. That information is encapsulated in a `context` structure.

This is how the `context`'s spec looks like. It is composed by a `sr_request:req()` and a `sr_state:state()` structures. Modules `sr_state` and `sr_request` are available in order to manipulate them.
```erlang
-type context() :: #{req := sr_request:req(), state := sr_state:state()}

.. In sr_request.erl ...

-opaque req() ::
#{ body => sr_json:json()
, headers := [{binary(), iodata()}]
, path := binary()
, bindings := #{atom() => any()}
}.

... In sr_state.erl ...

-opaque state() ::
#{ opts := sumo_rest:options()
, id => binary()
, entity => sumo:user_doc()
, module := module()
, user_opts := map()
}.
```

And this is the `from_ctx` implementation
```erlang
-spec from_ctx(sumo_rest_doc:context()) -> {ok, session()} | {error, iodata()}.
from_ctx(#{req := SrRequest, state := State}) ->
Json = sr_request:body(SrRequest),
{User, _} = sr_state:retrieve(user, State, undefined),
case from_json_internal(Json) of
{ok, Session} -> {ok, user(Session, User)};
MissingField -> MissingField
end.

```

### The Handlers
Now, the juicy part: The cowboy handlers. We have 4, two of them built on top of `sr_entitites_handler` and the other two built on `sr_single_entity_handler`.
Expand Down Expand Up @@ -350,38 +392,6 @@ is_authorized(Req, State) ->
end.
```

And then we redefined `handle_post/2` to use the authenticated user there:
```erlang
-spec handle_post(cowboy_req:req(), state()) ->
{{true, binary()}, cowboy_req:req(), state()}.
handle_post(Req, State) ->
#{user := {User, _}} = State,
try
{ok, Body, Req1} = cowboy_req:body(Req),
Json = sr_json:decode(Body),
case sr_sessions:from_json(Json) of
{error, Reason} ->
Req2 = cowboy_req:set_resp_body(sr_json:error(Reason), Req1),
{false, Req2, State};
{ok, Session} ->
FullSession = sr_sessions:user(Session, User),
sr_entities_handler:handle_post(FullSession, Req1, State)
end
catch
_:conflict ->
{ok, Req3} =
cowboy_req:reply(422, [], sr_json:error(<<"Duplicated entity">>), Req),
{halt, Req3, State};
_:badjson ->
Req3 =
cowboy_req:set_resp_body(
sr_json:error(<<"Malformed JSON request">>), Req),
{false, Req3, State}
end.
```

As you can see we still use `sr_entities_handler:handle_post/3` there, once we're past the parsing stage.

Finally, we did something similar in [`sr_single_session_handler`](test/sr_test/sr_single_session_handler.erl). We needed the same authentication mechanism, so we just _mix_ it _in_:
```erlang
-mixin([{ sr_sessions_handler
Expand Down
8 changes: 4 additions & 4 deletions rebar.lock
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@
{<<"lager">>,{pkg,<<"lager">>,<<"3.2.1">>},1},
{<<"mixer">>,{pkg,<<"inaka_mixer">>,<<"0.1.5">>},0},
{<<"quickrand">>,{pkg,<<"quickrand">>,<<"1.5.4">>},2},
{<<"ranch">>,{pkg,<<"ranch">>,<<"1.2.1">>},1},
{<<"ranch">>,{pkg,<<"ranch">>,<<"1.3.2">>},1},
{<<"sumo_db">>,{pkg,<<"sumo_db">>,<<"0.6.1">>},0},
{<<"trails">>,{pkg,<<"trails">>,<<"0.2.0">>},0},
{<<"uuid_erl">>,{pkg,<<"uuid_erl">>,<<"1.5.2-rc1">>},1},
{<<"uuid">>,{pkg,<<"uuid_erl">>,<<"1.5.2-rc1">>},1},
{<<"worker_pool">>,{pkg,<<"worker_pool">>,<<"2.0.1">>},1}]}.
[
{pkg_hash,[
Expand All @@ -24,9 +24,9 @@
{<<"lager">>, <<"EEF4E18B39E4195D37606D9088EA05BF1B745986CF8EC84F01D332456FE88D17">>},
{<<"mixer">>, <<"754630C0E60221B23E4D83ADF6E789A8B283855E23F9391EEC40980E6E800486">>},
{<<"quickrand">>, <<"47ADD4755CC5F209CBEFFD6F47C84061196CD7FAD99FD8FD12418EB0D06B939D">>},
{<<"ranch">>, <<"A6FB992C10F2187B46FFD17CE398DDF8A54F691B81768F9EF5F461EA7E28C762">>},
{<<"ranch">>, <<"E4965A144DC9FBE70E5C077C65E73C57165416A901BD02EA899CFD95AA890986">>},
{<<"sumo_db">>, <<"6D7BF7FEA90D8E41DEA894379A4E945622B8BFDDBB3EEF31D79B3D0CA3084056">>},
{<<"trails">>, <<"8A26C8F32B2A4D317830FAF55F034CC532D849547686806B83063AA1F65213D2">>},
{<<"uuid_erl">>, <<"D4022AB3F4F1A28E86EA15D4075CB0C57EC908D8AF1CA2E8AF28AA815EF93C3A">>},
{<<"uuid">>, <<"D4022AB3F4F1A28E86EA15D4075CB0C57EC908D8AF1CA2E8AF28AA815EF93C3A">>},
{<<"worker_pool">>, <<"B90273074898FA89434317991E00884DBBAFFAB5BFD964A7586317CD16FB18D4">>}]}
].
90 changes: 47 additions & 43 deletions src/sr_entities_handler.erl
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,7 @@
, model => atom()
, verbose => boolean()
}.
-type state() :: #{ opts => options()
, module => module()
, _ => _
}.
-type state() :: sr_state:state().
-export_type([state/0, options/0]).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Expand All @@ -45,7 +42,8 @@ rest_init(Req, Opts) ->
Req1 = announce_req(Req, Opts),
#{model := Model} = Opts,
Module = sumo_config:get_prop_value(Model, module),
{ok, Req1, #{opts => Opts, module => Module}}.
State = sr_state:new(Opts, Module),
{ok, Req1, State}.

%% @doc Retrieves the list of allowed methods from Trails metadata.
%% Parses the metadata associated with this path and returns the
Expand All @@ -54,7 +52,7 @@ rest_init(Req, Opts) ->
-spec allowed_methods(cowboy_req:req(), state()) ->
{[binary()], cowboy_req:req(), state()}.
allowed_methods(Req, State) ->
#{opts := #{path := Path}} = State,
#{path := Path} = sr_state:opts(State),
Trail = trails:retrieve(Path),
Metadata = trails:metadata(Trail),
Methods = [atom_to_method(Method) || Method <- maps:keys(Metadata)],
Expand All @@ -75,20 +73,19 @@ resource_exists(Req, State) ->
-spec content_types_accepted(cowboy_req:req(), state()) ->
{[{{binary(), binary(), '*'}, atom()}], cowboy_req:req(), state()}.
content_types_accepted(Req, State) ->
#{opts := #{path := Path}} = State,
{Method, Req2} = cowboy_req:method(Req),
try
Trail = trails:retrieve(Path),
Metadata = trails:metadata(Trail),
AtomMethod = method_to_atom(Method),
#{AtomMethod := #{consumes := Consumes}} = Metadata,
Handler = compose_handler_name(AtomMethod),
RetList = [{iolist_to_binary(X), Handler} || X <- Consumes],
{RetList, Req2, State}
catch
_:_ ->
{[{{<<"application">>, <<"json">>, '*'}, handle_post}], Req, State}
end.
#{path := Path} = sr_state:opts(State),
{Method, Req2} = cowboy_req:method(Req),
try
Trail = trails:retrieve(Path),
Metadata = trails:metadata(Trail),
AtomMethod = method_to_atom(Method),
#{AtomMethod := #{consumes := Consumes}} = Metadata,
Handler = compose_handler_name(AtomMethod),
RetList = [{iolist_to_binary(X), Handler} || X <- Consumes],
{RetList, Req2, State}
catch
_:_ -> {[{{<<"application">>, <<"json">>, '*'}, handle_post}], Req, State}
end.

%% @doc Always returns "application/json" with <code>handle_get</code>.
%% @see cowboy_rest:content_types_provided/2
Expand All @@ -97,20 +94,19 @@ content_types_accepted(Req, State) ->
-spec content_types_provided(cowboy_req:req(), state()) ->
{[{binary(), atom()}], cowboy_req:req(), state()}.
content_types_provided(Req, State) ->
#{opts := #{path := Path}} = State,
{Method, Req2} = cowboy_req:method(Req),
try
Trail = trails:retrieve(Path),
Metadata = trails:metadata(Trail),
AtomMethod = method_to_atom(Method),
#{AtomMethod := #{produces := Produces}} = Metadata,
Handler = compose_handler_name(AtomMethod),
RetList = [{iolist_to_binary(X), Handler} || X <- Produces],
{RetList, Req2, State}
catch
_:_ ->
{[{<<"application/json">>, handle_get}], Req, State}
end.
#{path := Path} = sr_state:opts(State),
{Method, Req2} = cowboy_req:method(Req),
try
Trail = trails:retrieve(Path),
Metadata = trails:metadata(Trail),
AtomMethod = method_to_atom(Method),
#{AtomMethod := #{produces := Produces}} = Metadata,
Handler = compose_handler_name(AtomMethod),
RetList = [{iolist_to_binary(X), Handler} || X <- Produces],
{RetList, Req2, State}
catch
_:_ -> {[{<<"application/json">>, handle_get}], Req, State}
end.

%% @doc Returns the list of all entities.
%% Fetches the entities from <strong>SumoDB</strong> using the
Expand All @@ -120,9 +116,8 @@ content_types_provided(Req, State) ->
-spec handle_get(cowboy_req:req(), state()) ->
{iodata(), cowboy_req:req(), state()}.
handle_get(Req, State) ->
#{ opts := #{model := Model}
, module := Module
} = State,
#{model := Model} = sr_state:opts(State),
Module = sr_state:module(State),
{Qs, Req1} = cowboy_req:qs_vals(Req),
Conditions = [ {binary_to_atom(Name, unicode),
Value} || {Name, Value} <- Qs ],
Expand All @@ -142,16 +137,24 @@ handle_get(Req, State) ->
{JSON, Req1, State}.

%% @doc Creates a new entity.
%% To parse the body, it uses <code>from_json/2</code> from the
%% To parse the body, it uses <code>from_ctx</code> or
%% <code>from_json/2</code> from the
%% <code>model</code> provided in the options.
-spec handle_post(cowboy_req:req(), state()) ->
{{true, binary()} | false | halt, cowboy_req:req(), state()}.
handle_post(Req, State) ->
#{module := Module} = State,
Module = sr_state:module(State),
try
{ok, Body, Req1} = cowboy_req:body(Req),
Json = sr_json:decode(Body),
case Module:from_json(Json) of
{SrRequest, Req1} = sr_request:from_cowboy(Req),
Result = case erlang:function_exported(Module, from_ctx, 1) of
false ->
Json = sr_request:body(SrRequest),
Module:from_json(Json);
true ->
Context = #{req => SrRequest, state => State},
Module:from_ctx(Context)
end,
case Result of
{error, Reason} ->
Req2 = cowboy_req:set_resp_body(sr_json:error(Reason), Req1),
{false, Req2, State};
Expand All @@ -175,7 +178,8 @@ handle_post(Req, State) ->
-spec handle_post(sumo:user_doc(), cowboy_req:req(), state()) ->
{{true, binary()}, cowboy_req:req(), state()}.
handle_post(Entity, Req1, State) ->
#{opts := #{model := Model, path := Path}, module := Module} = State,
#{model := Model, path := Path} = sr_state:opts(State),
Module = sr_state:module(State),
case erlang:function_exported(Module, duplication_conditions, 1) of
false -> proceed;
true ->
Expand Down
55 changes: 55 additions & 0 deletions src/sr_request.erl
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
-module(sr_request).

-export([ from_cowboy/1
, body/1
, headers/1
, path/1
, bindings/1
]).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Types
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

-opaque req() ::
#{ body := sr_json:json()
, headers := [{binary(), iodata()}]
, path := binary()
, bindings := #{atom() => any()}
}.

-export_type [req/0].

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Constructor, getters/setters
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

-spec from_cowboy(cowboy_req:req()) -> {req(), cowboy_req:req()}.
from_cowboy(CowboyReq) ->
{ok, RawBody, CowboyReq1} = cowboy_req:body(CowboyReq),
Body = sr_json:decode(RawBody),
{Headers, CowboyReq2} = cowboy_req:headers(CowboyReq1),
{Path, CowboyReq3} = cowboy_req:path(CowboyReq2),
{BindingsList, CowboyReq4} = cowboy_req:bindings(CowboyReq3),
Request = #{ body => Body
, headers => Headers
, path => Path
, bindings => maps:from_list(BindingsList)
},
{Request, CowboyReq4}.

-spec body(req()) -> sr_json:json() | undefined.
body(#{body := Body}) ->
Body.

-spec headers(req()) -> [{binary(), iodata()}].
headers(#{headers := Headers}) ->
Headers.

-spec path(req()) -> binary().
path(#{path := Path}) ->
Path.

-spec bindings(req()) -> #{atom() => any()}.
bindings(#{bindings := Bindings}) ->
Bindings.
Loading