nova_handlers (nova v0.14.3)
View SourceThis module is responsible for all the different return types a controller have. Nova is constructed in such way that it's really easy to extend it by using handlers. A handler is basically a module consisting of a function of arity 4. We will show an example of this.
If you implement the following module:
-module(my_handler). -export([init/0, handle_console]).
init() -> nova_handlers:register_handler(console, {my_handler, handle_console}).
handle_console({console, Format, Args}, {Module, Function}, State) -> io:format("~n=====================~n", []). io:format("~p:~p was called.~n", []), io:format("State: ~p~n", [State]), io:format(Format, Args), io:format("~n=====================~n", []), {ok, 200, #{}, EmptyBinary}.
The init/0 should be invoked from your applications supervisor and will register the module my_handler as handler of the return type {console, Format, Args}. This means that you can return this tuple in a controller which invokes my_handler:handle_console/4.
A handler can return two different types
{ok, StatusCode, Headers, Body} - This will return a proper reply to the requester.
{error, Reason} - This will render a 500 page to the user.
Summary
Functions
Fetches the handler identified with 'Handle' and returns the callback function for it.
Registers a new handler. This can then be used in a nova controller by returning a tuple where the first element is the name of the handler.
Unregisters a handler and makes it unavailable for all controllers.
Types
-type handler_callback() :: {Module :: atom(), Function :: atom()} | fun((...) -> handler_return()).
-type handler_return() :: {ok, State2 :: nova:state()} | {Module :: atom(), State :: nova:state()} | {error, Reason :: any()}.
Functions
-spec get_handler(Handle :: atom()) -> {ok, Callback :: handler_callback()} | {error, not_found}.
Fetches the handler identified with 'Handle' and returns the callback function for it.
-spec register_handler(Handle :: atom(), Callback :: handler_callback()) -> ok | {error, Reason :: atom()}.
Registers a new handler. This can then be used in a nova controller by returning a tuple where the first element is the name of the handler.
-spec unregister_handler(Handle :: atom()) -> ok.
Unregisters a handler and makes it unavailable for all controllers.