|
| 1 | +use ajj::HandlerCtx; |
| 2 | +use std::net::SocketAddr; |
| 3 | + |
| 4 | +#[tokio::main] |
| 5 | +async fn main() -> eyre::Result<()> { |
| 6 | + let router = make_router(); |
| 7 | + |
| 8 | + // Serve via `POST` on `/` and Websockets on `/ws` |
| 9 | + let axum = router.clone().into_axum_with_ws("/", "/ws"); |
| 10 | + |
| 11 | + // Now we can serve the router on a TCP listener |
| 12 | + let addr = SocketAddr::from(([127, 0, 0, 1], 0)); |
| 13 | + let listener = tokio::net::TcpListener::bind(addr).await?; |
| 14 | + |
| 15 | + println!("Listening for POST on {}/", listener.local_addr()?); |
| 16 | + println!("Listening for WS on {}/ws", listener.local_addr()?); |
| 17 | + |
| 18 | + println!("use Ctrl-C to stop"); |
| 19 | + axum::serve(listener, axum).await.map_err(Into::into) |
| 20 | +} |
| 21 | + |
| 22 | +fn make_router() -> ajj::Router<()> { |
| 23 | + ajj::Router::<()>::new() |
| 24 | + .route("helloWorld", || async { |
| 25 | + tracing::info!("serving hello world"); |
| 26 | + Ok::<_, ()>("Hello, world!") |
| 27 | + }) |
| 28 | + .route("addNumbers", |(a, b): (u32, u32)| async move { |
| 29 | + tracing::info!("serving addNumbers"); |
| 30 | + Ok::<_, ()>(a + b) |
| 31 | + }) |
| 32 | + .route("notify", |ctx: HandlerCtx| async move { |
| 33 | + // Check if notifications are enabled for the connection. |
| 34 | + if !ctx.notifications_enabled() { |
| 35 | + // This error will appear in the ResponsePayload's `data` field. |
| 36 | + return Err("notifications are disabled"); |
| 37 | + } |
| 38 | + |
| 39 | + let req_id = 15u8; |
| 40 | + |
| 41 | + // Spawn a task to send the notification after a short delay. |
| 42 | + ctx.spawn_with_ctx(|ctx| async move { |
| 43 | + // something expensive goes here |
| 44 | + let result = 100_000_000; |
| 45 | + let _ = ctx |
| 46 | + .notify(&serde_json::json!({ |
| 47 | + "req_id": req_id, |
| 48 | + "result": result, |
| 49 | + })) |
| 50 | + .await; |
| 51 | + }); |
| 52 | + |
| 53 | + // Return the request ID immediately. |
| 54 | + Ok(req_id) |
| 55 | + }) |
| 56 | +} |
0 commit comments