We provide several libraries for working with Datastar:
starfederation.datastar.clojure.protocols/SSEGenerator
protocol as well as
several libraries implementing it to work with specific ring adapters.There currently are adapter implementations for:
If you want to roll your own adapter implementation, see implementing-adapters.
library | deps coordinate |
---|---|
SDK | |
http-kit | |
ring | |
brotli | |
Core SDK malli schemas | |
Http-kit malli schemas | |
Ring malli schemas |
ring.core.protocols/StreamableResponseBody
)By convention SDK adapters provide a single ->sse-response
function. This
function returns a valid ring response tailored to work with the ring
adapter it is made for. This function will receive an implementation of
SSEGenerator
protocol also tailored to the ring adapter used.
You then use the Datastar SDK functions with the SSE generator.
Start by requiring the main API and an adapter. With Http-kit for instance:
(require '[starfederation.datastar.clojure.api :as d*]
'[starfederation.datastar.clojure.adapter.http-kit :as hk-gen])
Using the adapter you create ring responses in your handlers:
(defn sse-handler [request]
(hk-gen/->sse-response request
{hk-gen/on-open
(fn [sse-gen]
(d*/patch-elements! sse-gen "<div>test</div>")
(d*/close-sse! sse-gen))}))
In the callback we use the SSE generator sse-gen
with the Datastar SDK functions.
Depending on the adapter you use, you can keep the SSE generator open by storing it somewhere and use it later:
(def !connections (atom #{}))
(defn sse-handler [request]
(hk-gen/->sse-response request
{hk-gen/on-open
(fn [sse-gen]
(swap! !connections conj sse-gen))
hk-gen/on-close
(fn [sse-gen status]
(swap! !connections disj sse-gen))}))
(defn broadcast-elements! [elements]
(doseq [c @!connections]
(d*/patch-elements! c elements)))
This SDK is essentially a tool to manage SSE connections with helpers to format events the way the Datastar framework expects them on the front end.
It provides advanced functionality for managing several aspects of SSE.
You can find more information in several places:
->sse-response
function you are using.Can you improve this documentation? These fine people already did:
Jeremy Schoffen, Jérémy, JeremS, Teodor Heggelund & DosbolEdit on GitHub
cljdoc builds & hosts documentation for Clojure/Script libraries
Ctrl+k | Jump to recent docs |
← | Move to previous article |
→ | Move to next article |
Ctrl+/ | Jump to the search field |