|
| 1 | +//! Run with auto-generated schemas for `Json<Product>` using `schemars`: |
| 2 | +//! cargo run --example schema --features schemars |
| 3 | +//! |
| 4 | +//! Run with primitive schemas only: |
| 5 | +//! cargo run --example schema |
| 6 | +
|
| 7 | +use restate_sdk::prelude::*; |
| 8 | +use schemars::JsonSchema; |
| 9 | +use serde::{Deserialize, Serialize}; |
| 10 | +use std::time::Duration; |
| 11 | + |
| 12 | +#[derive(Serialize, Deserialize, JsonSchema)] |
| 13 | +struct Product { |
| 14 | + id: String, |
| 15 | + name: String, |
| 16 | + price_cents: u32, |
| 17 | +} |
| 18 | + |
| 19 | +#[restate_sdk::service] |
| 20 | +trait CatalogService { |
| 21 | + async fn get_product_by_id(product_id: String) -> Result<Json<Product>, HandlerError>; |
| 22 | + async fn save_product(product: Json<Product>) -> Result<String, HandlerError>; |
| 23 | + async fn is_in_stock(product_id: String) -> Result<bool, HandlerError>; |
| 24 | +} |
| 25 | + |
| 26 | +struct CatalogServiceImpl; |
| 27 | + |
| 28 | +impl CatalogService for CatalogServiceImpl { |
| 29 | + async fn get_product_by_id( |
| 30 | + &self, |
| 31 | + ctx: Context<'_>, |
| 32 | + product_id: String, |
| 33 | + ) -> Result<Json<Product>, HandlerError> { |
| 34 | + ctx.sleep(Duration::from_millis(50)).await?; |
| 35 | + Ok(Json(Product { |
| 36 | + id: product_id, |
| 37 | + name: "Sample Product".to_string(), |
| 38 | + price_cents: 1995, |
| 39 | + })) |
| 40 | + } |
| 41 | + |
| 42 | + async fn save_product( |
| 43 | + &self, |
| 44 | + _ctx: Context<'_>, |
| 45 | + product: Json<Product>, |
| 46 | + ) -> Result<String, HandlerError> { |
| 47 | + Ok(product.0.id) |
| 48 | + } |
| 49 | + |
| 50 | + async fn is_in_stock( |
| 51 | + &self, |
| 52 | + _ctx: Context<'_>, |
| 53 | + product_id: String, |
| 54 | + ) -> Result<bool, HandlerError> { |
| 55 | + Ok(!product_id.contains("out-of-stock")) |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +#[tokio::main] |
| 60 | +async fn main() { |
| 61 | + tracing_subscriber::fmt::init(); |
| 62 | + HttpServer::new(Endpoint::builder().bind(CatalogServiceImpl.serve()).build()) |
| 63 | + .listen_and_serve("0.0.0.0:9080".parse().unwrap()) |
| 64 | + .await; |
| 65 | +} |
0 commit comments