Skip to content

Instantly share code, notes, and snippets.

@autodidaddict
Last active September 10, 2019 13:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save autodidaddict/4c14d5dc6bec1c2470beede314aef8f4 to your computer and use it in GitHub Desktop.
Save autodidaddict/4c14d5dc6bec1c2470beede314aef8f4 to your computer and use it in GitHub Desktop.
Waxosuit Key-Value Tutorial
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