Packages

An Elixir client for the Polymarket API.

Current section

Files

Jump to
ex_polymarket lib websocket handler.ex
Raw

lib/websocket/handler.ex

defmodule Polymarket.WebSocket.Handler do
@moduledoc """
Behaviour for modules that handle decoded Polymarket websocket events.
A handler module is injected into the websocket through its start options
(see `Polymarket.WebSocket.start_link/1`) and is invoked by
`Polymarket.WebSocket.MessageHandler` for every event that is successfully
decoded off the feed.
A handler typically performs side effects with the event (persisting it,
forwarding it, and so on) and returns `{:noreply, state}`. It may also return
`{:reply, frame, state}` to send a frame back over the websocket, for example
to subscribe to additional assets in response to an event.
## Example
defmodule MyHandler do
@behaviour Polymarket.WebSocket.Handler
@impl true
def handle_event(%Polymarket.Schemas.PriceChangeEvent{} = event, state) do
Logger.info("price change: \#{inspect(event)}")
{:noreply, state}
end
def handle_event(_event, state), do: {:noreply, state}
end
"""
alias Polymarket.WebSocket
@typedoc "A decoded event struct from `Polymarket.Schemas`."
@type event :: struct()
@typedoc "The websocket process state."
@type state :: WebSocket.t()
@typedoc "A single websocket text frame to send back to the server."
@type frame :: {:text, String.t()}
@doc """
Invoked for every event that is successfully decoded from the feed.
Must return either `{:noreply, state}` to update the websocket state without
replying, or `{:reply, frame, state}` to send `frame` back over the websocket
before continuing.
"""
@callback handle_event(event(), state()) ::
{:reply, frame(), state()} | {:noreply, state()}
end