diff --git a/README.md b/README.md index d2e6a80..a4f5d79 100644 --- a/README.md +++ b/README.md @@ -8,14 +8,22 @@ A JSON-RPC 2.0 server handler for Rust, with automatic generation of a TypeScrip yerpc includes (optional) integration with `axum` and `tokio-tungstenite` for easy setup and usage. Enable the `support-axum` and `support-tungstenite` feature flags for these integrations. ## Example +```bash +cargo new my-example && cd my-example +cargo add yerpc --features support-axum +cargo add tokio --features rt-multi-thread +cargo add axum serde_json typescript_type_def +``` + +**src/main.rs** ```rust -use axum::{ - extract::ws::WebSocketUpgrade, http::StatusCode, response::Response, routing::get, Router, -}; +use axum::Extension; +use axum::{Router, extract::ws::WebSocketUpgrade, response::Response, routing::get}; use std::net::SocketAddr; -use yerpc::{rpc, RpcClient, RpcSession}; use yerpc::axum::handle_ws_rpc; +use yerpc::{RpcClient, RpcSession, rpc}; +#[derive(Clone)] struct Api; #[rpc(all_positional)] @@ -30,32 +38,32 @@ impl Api { #[tokio::main] async fn main() -> Result<(), std::io::Error> { - let api = Api {} + let api = Api {}; let app = Router::new() .route("/rpc", get(handler)) .layer(Extension(api)); let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); eprintln!("listening on {}", addr); - axum::Server::bind(&addr) - .serve(app.into_make_service()) + let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); + axum::serve(listener, app.into_make_service()) .await .unwrap(); Ok(()) } -async fn handler( - ws: WebSocketUpgrade, - Extension(api): Extension, -) -> Response { +async fn handler(ws: WebSocketUpgrade, Extension(api): Extension) -> Response { let (client, out_channel) = RpcClient::new(); let session = RpcSession::new(client, api); handle_ws_rpc(ws, out_channel, session).await } +``` -#[test] -fn write_files() { - use std::path::Path; +**build.rs** +```rust +use crate::{write_ts_bindings, write_openrpc}; +use std::path::Path; +fn build() { write_ts_bindings(Path::new("typescript/generated")); write_openrpc(Path::new(".")); } @@ -63,5 +71,5 @@ fn write_files() { Now you can connect any JSON-RPC client to `ws://localhost:3000/rpc` and call the `shout` and `add` methods. -After running `cargo test` you will find an autogenerated TypeScript client in the `typescript/generated` folder and an `openrpc.json` file in the root of your project. +After running `cargo build` you will find an autogenerated TypeScript client in the `typescript/generated` folder and an `openrpc.json` file in the root of your project. See [`examples/axum`](examples/axum) for a full usage example with Rust server and TypeScript client for a chat server.