spin_sdk/key_value.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
//! Spin key-value persistent storage
//!
//! This module provides a generic interface for key-value storage, which may be implemented by the host various
//! ways (e.g. via an in-memory table, a local file, or a remote database). Details such as consistency model and
//! durability will depend on the implementation and may vary from one to store to the next.
use super::wit::v2::key_value;
#[cfg(feature = "json")]
use serde::{de::DeserializeOwned, Serialize};
#[doc(inline)]
pub use key_value::{Error, Store};
impl Store {
/// Open the default store.
///
/// This is equivalent to `Store::open("default")`.
pub fn open_default() -> Result<Self, Error> {
Self::open("default")
}
}
impl Store {
#[cfg(feature = "json")]
/// Serialize the given data to JSON, then set it as the value for the specified `key`.
pub fn set_json<T: Serialize>(
&self,
key: impl AsRef<str>,
value: &T,
) -> Result<(), anyhow::Error> {
Ok(self.set(key.as_ref(), &serde_json::to_vec(value)?)?)
}
#[cfg(feature = "json")]
/// Deserialize an instance of type `T` from the value of `key`.
pub fn get_json<T: DeserializeOwned>(
&self,
key: impl AsRef<str>,
) -> Result<Option<T>, anyhow::Error> {
let Some(value) = self.get(key.as_ref())? else {
return Ok(None);
};
Ok(serde_json::from_slice(&value)?)
}
}