Last active
September 10, 2019 13:19
-
-
Save autodidaddict/4c14d5dc6bec1c2470beede314aef8f4 to your computer and use it in GitHub Desktop.
Waxosuit Key-Value Tutorial
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extern crate wascap_guest as guest; | |
#[macro_use] | |
extern crate serde_derive; | |
use guest::prelude::*; | |
call_handler!(handle_call); | |
pub fn handle_call(ctx: &CapabilitiesContext, operation: &str, msg: &[u8]) -> CallResult { | |
match operation { | |
http::TYPE_URL_HTTP_REQUEST => handle_counter(ctx, msg), | |
core::TYPE_URL_HEALTH_REQUEST => Ok(vec![]), | |
_ => Err("bad dispatch".into()), | |
} | |
} | |
fn handle_counter(ctx: &CapabilitiesContext, payload: impl Into<http::Request>) -> CallResult { | |
let req = payload.into(); | |
match req.method.as_ref() { | |
"GET" => query_counter(ctx.kv()), | |
_ => increment_counter(ctx.kv()), | |
} | |
} | |
fn query_counter(kv: &KeyValueStore) -> CallResult { | |
let val: i32 = kv.get("demo:counter")?.unwrap().parse().unwrap(); | |
Ok(protobytes(http::Response::json(CounterData { counter: val }, 200, "OK")?) | |
} | |
fn increment_counter(kv: &KeyValueStore) -> CallResult { | |
kv.atomic_add("demo:counter", 1)?; | |
Ok(protobytes(http::Response::ok()?) | |
} | |
#[derive(Debug, Serialize)] | |
struct CounterData { | |
counter: i32, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment