The key-value storage in W3bstream is specifically designed for storing data that can be retrieved using a unique key. This functionality proves useful for various purposes, such as storing application settings and maintaining status information.
To store an object called "myObj" in the key-value database, a W3bstream applet can utilize the SetDB function.
The example below demonstrates how you can store and retrieve an integer value from the key-value storage:
import { GetDB, SetDB } from"@w3bstream/wasm-sdk";export { alloc } from"@w3bstream/wasm-sdk";exportfunctionmy_habdler(rid:i32):i32 {// Read the data stored under the key "users_count"let value =GetDB("users_count");// Convert the string to i32let users_count = value ?parseInt(value) :0;// store the new valuelet result =SetDB("users_count", (i32(users_count) +1));return0;}
use ws_sdk::database::kv::{get, set};use ws_sdk::log::log_info;#[no_mangle]pubextern"C"fnmy_handler(_rid:i32) ->i32 {// Read the data stored under the key "users_count"let value =get("users_count").unwrap_or("0".into());// Convert the bytes vector to string and parse it to i32let int_value =String::from_utf8(value).unwrap().parse::<i32>().unwrap();// Log the valuelog_info(&format!("Current users count: {}", int_value));// Increment and store the incremented the value as string byteslet result =set("users_count", (int_value +1).to_string().into_bytes());0}// Add a main() if required by the compilerfnmain() { }