chyabrung-cli 0.2.1

The `chy` command line tool for Chyabrung: scaffolding, dev server with hot reload, builds, generators, migrations and one-command deploys
//! Live updates: Server-Sent Events and a WebSocket echo.

use chyabrung::prelude::*;
use chyabrung::ws::Message;
use std::time::Duration;

/// `GET /api/events`: sends a `tick` event every second.
pub async fn events() -> Sse {
    let stream = futures_util::stream::unfold(0u32, |n| async move {
        tokio::time::sleep(Duration::from_secs(1)).await;
        Some((Event::default().event("tick").id(n.to_string()).data(format!("{{\"n\":{n}}}")), n + 1))
    });
    Sse::new(stream).keep_alive(Duration::from_secs(15))
}

/// `GET /ws`: a WebSocket that echoes every text message.
pub async fn socket(ws: WebSocketUpgrade) -> Response {
    ws.on_upgrade(|mut socket| async move {
        let _ = socket.send_text("welcome to chyabrung").await;
        while let Some(Ok(msg)) = socket.recv().await {
            match msg {
                Message::Text(t) => {
                    if socket.send_text(format!("echo: {t}")).await.is_err() {
                        break;
                    }
                }
                Message::Close(_) => break,
                _ => {}
            }
        }
    })
}