Bastion.Channel
lib/channel.march — Bastion.Channel: connection type and helpers for channel handlers.
Channel handlers are ordinary March modules that implement three functions:
fn join(conn, topic, params_json) : Result(ChannelConn, String)
fn handle_in(conn, event, payload_json) : ChannelConn
fn handle_out(conn, event, payload_json) : Result(ChannelConn, String)A ChannelConn flows through every callback, carrying user-set assigns, the joined topic, the connection's unique ID, and a push function for sending server-initiated messages back to this client.
── Minimal channel handler ───────────────────────────────────────────────────
mod MyApp.RoomChannel do
import Bastion.Channel
fn join(conn, topic, _params) do
let room_id = String.replace_prefix(topic, "room:", "")
conn
|> Channel.assign("room_id", room_id)
|> Ok()
end
fn handle_in(conn, "message:new", payload_json) do
Bastion.PubSub.broadcast(Channel.topic(conn), "message:new", payload_json)
conn
end
fn handle_in(conn, _event, _payload) do conn end
fn handle_out(conn, _event, _payload) do Ok(conn) end
endTypes
Functions
Store a string key/value in the channel connection assigns.
Replaces any existing value with the same key.
conn |> Channel.assign("room_id", "42")
|> Channel.assign("role", "moderator")Broadcast an event to all subscribers of a topic, excluding this connection.
Shorthand for `Bastion.PubSub.broadcast_from/4` using this conn's ID.
conn |> Channel.broadcast_from("room:42", "typing:start", "{}")Return the unique connection ID used to identify this socket in PubSub.
Look up an assign by key. Returns Some(value) or None.
Channel.get_assign(conn, "room_id") -- Some("42") or NoneBuild a new ChannelConn. Called by Bastion.ChannelServer when a join is accepted; user code does not normally need to call this directly.
Push an event directly to this connection's client.
Use in handle_in to reply to only the sender, rather than broadcasting to
all topic subscribers.
conn |> Channel.push("error", "{\"code\":\"not_found\"}")Return the subscription ID used when registering with PubSub for a topic. Format: "conn:<conn_id>:<topic>"
Return the joined topic string (e.g. \