Hooks, State and Streaming
Hooks and State
Example: Hooks Around Every Request shows its code and downloads as a project.
src/hooks.rs holds what runs outside any one route:
pub struct User(pub String);
/// Once, before the server listens. A failure stops it with the reason.
async fn init() -> Result<()> {
wisp::provide(Db::connect(&wisp::env("DATABASE_URL").or_status(500)?).await?);
Ok(())
}
/// Before every page, action and endpoint (and 404), not static files.
fn before(cx: &mut Cx) -> Result<()> {
cx.set_header("x-frame-options", "DENY");
if let Some(name) = cx.signed_cookie("user") {
let user = User(name.to_string());
cx.set(user);
}
if cx.path().starts_with("/admin") && cx.get::<User>().is_none() {
return redirect("/login");
}
Ok(())
}
before may return nothing, Result<()>, a Response (sent instead of the route) or Option<Response>. Headers it sets stay on error pages. init takes no cx. Routes use the pub types of src/hooks.rs without a use. The build rejects any other pub fn there.
Values
| API | What it does |
|---|---|
wisp::provide(value) | makes a value (pool, client) available as wisp::state::<T>()? (a logged 500 if none was) |
static X: Shared<Vec<Todo>> = Shared::new(Vec::new()); | in-memory value all requests share: X.lock().push(todo). Do not hold the guard across .await |
static X: Table<Todo> = Table::new(); | rows under ids it gives |
Table::saved("todos") | the same, kept in the store (WISP_DATA, or a database via wisp::Store) |
#[derive(Rest)] | gives the type a saved Note::table() that a +server.rs serves (APIs and platforms) |
cx.set(value) / cx.get::<T>() / cx.take::<T>() | hand a value along one request |
cx.bearer() / cx.host() | the Authorization: Bearer token / the Host |
cx.delete_cookie(name) | deletes a cookie |
cx.flash("Saved") | message for the next page, shown once by {@flash} |
cx.after(|| ...) | runs once the handler is through (a log line, a revalidate_tag) |
Table methods: add(todo) returns the id. get(id), all() and find(|t| ...) return Row { id, value }. update(id, |t| t.done = true). remove(id).
Streaming
// src/routes/clock/+server.rs
fn get() -> Response {
Response::events(|events| async move {
loop {
events.event(&now()).await?;
wisp::sleep(Duration::from_secs(1)).await;
}
})
}
Response::stream(content_type, |body| async move { ... }): the closure writes with aSenderin its own task. Eachsendgoes out at once. The body ends when the closure returns.Response::eventsis the same for server-sent events.Sender::eventwrites one event. A page listens withlisten(url, ...)ornew EventSource(url).- A send fails once the client leaves, so
?stops the closure.
Streaming a Page: {#await}
<h1>${user.name}</h1>
{#await stats(user.id)}
<p>Counting…</p>
{:then s}
<p>${s.posts} posts</p>
{:catch e}
<p>No stats: ${e}</p>
{/await}
The page goes out at once with the pending markup, and the response stays open. Each answer follows after </html> as it finishes, in completion order, with a one-line script that moves it into place. Without JS the answers stay at the end of the page.
- The expression is a future (
stats(id),async { ... }). It runs after the page is sent, so it isSend + 'staticand owns what it reads. {:then v}gets aResult'sOkvalue or any other value.{:catch e}gets anErras text.- A branch has no
cx, and no page browser code ({:x},on:,bind:). Components in a branch are live. - A future that fails with no
{:catch}, panics or passesWISP_HANDLER_TIMEOUTshowsSomething went wrong. - Only a page's own markup awaits, and not with
SSR = false. - With
CACHE,CACHE_PUBLICorPRERENDER, Wisp waits and keeps the answer. A future that readscxbecomes a hole (Holes).
Client Code
Browser reactivity is in Browser code. The build sends only the Rust values the script uses, as JSON. live.js runs it and wisp.js does forms and the router. Dispatch wisp:refresh on the document to morph the current page in again.
Is This Page Useful?