W3WS.Handler behaviour (w3ws v0.3.0)
Base module for W3WS handlers
W3WS.Env
, W3WS.Event
and W3WS.RawEvent
are aliased into your handler
automatically when you use W3WS.Handler
.
Define the initialize/1
function to configure the handler state. This
state will be passed to handle_event/2
. This callback is optional.
Define the handle_event/2
function to handle events in your handler. Events are not
retried on error so be sure you have any necessary error handling or retry logic in place
if you cannot miss any events.
Define the settled?/1
function to determine if the handler has settled. This
callback is optional. The default implementation always returns true
.
Example
defmodule MyHandler do
use W3WS.Handler
@impl W3WS.Handler
def initialize(_opts) do
{:ok, nil}
end
@impl W3WS.Handler
def handle_event(%Env{decoded?: true, event: %Event{} = event}, _state) do
# inspect decoded events
IO.inspect(event)
end
def handle_event(_env, _state) do
# ignore non-decoded events
:ok
end
@impl W3WS.Handler
def settled?(_state), do: true
end
Summary
Callbacks
Callback invoked for each received event
Callback invoked to initialize the handler
Callback invoked to determine if the handler is settled
Functions
Call the handler with the given event
Initialize the handler.
Determine if the handler is settled. This only applies to module-based handlers. For
other handler types this always returns true
.
Types
state()
@type state() :: any()
Callbacks
handle_event(env, state)
@callback handle_event(env :: W3WS.Env.t(), state :: state()) :: any()
Callback invoked for each received event
initialize(t)
Callback invoked to initialize the handler
settled?(state)
Callback invoked to determine if the handler is settled
Functions
apply_handler(env, handler, state)
@spec apply_handler( env :: W3WS.Env.t(), handler :: t(), state :: any() ) :: pid() | {pid(), reference()}
Call the handler with the given event
Examples
iex> apply_handler(%W3WS.Env{}, fn _env -> :ok end, nil) |> is_pid()
true
iex> apply_handler(%W3WS.Env{}, W3WS.Handler.DefaultHandler, nil) |> is_pid()
true
iex> apply_handler(%W3WS.Env{}, {W3WS.Handler.DefaultHandler, :handle, []}, nil) |> is_pid()
true
iex> apply_handler(%W3WS.Env{}, "something", nil)
** (RuntimeError) Invalid handler: "something"
initialize(handler, opts \\ [])
Initialize the handler.
settled?(module, state)
Determine if the handler is settled. This only applies to module-based handlers. For
other handler types this always returns true
.