spin_sdk/
key_value.rs

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