Datastar.SSE (DatastarEx v0.1.0)

View Source

Server-Sent Event (SSE) generator for streaming updates to clients.

This module provides functionality for creating and managing SSE connections, sending events, and handling the streaming lifecycle.

Example

conn
|> put_resp_content_type("text/event-stream")
|> send_chunked(200)
|> Datastar.SSE.new()
|> Datastar.SSE.send_event("my-event", "data content")

Summary

Functions

Marks the SSE connection as closed.

Checks if the SSE connection is closed.

Creates a new SSE generator from a Plug connection.

Sends an SSE event to the client.

Sends an SSE event and raises on error.

Types

t()

@type t() :: %Datastar.SSE{closed: boolean(), conn: Plug.Conn.t()}

Functions

close(sse)

@spec close(t()) :: t()

Marks the SSE connection as closed.

closed?(sse)

@spec closed?(t()) :: boolean()

Checks if the SSE connection is closed.

new(conn)

@spec new(Plug.Conn.t()) :: t()

Creates a new SSE generator from a Plug connection.

The connection must already have:

  • Content type set to "text/event-stream"
  • Response status set
  • Chunked response initiated via send_chunked/2

Example

conn
|> put_resp_content_type("text/event-stream")
|> send_chunked(200)
|> Datastar.SSE.new()

send_event(sse, event_type, data_lines, opts)

@spec send_event(t(), String.t(), [String.t()] | String.t(), keyword()) ::
  {:ok, t()} | {:error, term()}

Sends an SSE event to the client.

Parameters

  • sse - The SSE generator struct
  • event_type - The event type (e.g., "datastar-patch-elements")
  • data_lines - A list of data lines or a single string
  • opts - Optional keyword list with:
    • :event_id - Event ID for client tracking
    • :retry - Retry duration in milliseconds

Example

sse
|> send_event("my-event", ["line1", "line2"], event_id: "123", retry: 5000)

send_event!(sse, event_type, data_lines, opts \\ [])

@spec send_event!(t(), String.t(), [String.t()] | String.t(), keyword()) :: t()

Sends an SSE event and raises on error.

Same as send_event/4 but raises if the event cannot be sent. Returns the updated SSE generator on success.

Example

sse
|> send_event!("my-event", "data")
|> send_event!("another-event", "more data")