use std::fmt::Display;
use anyhow::{anyhow, Result};
use async_trait::async_trait;
use noosphere_common::{ConditionalSend, ConditionalSync};
use serde::{de::DeserializeOwned, Serialize};
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
pub trait KeyValueStore: Clone + ConditionalSync {
async fn set_key<K, V>(&mut self, key: K, value: V) -> Result<()>
where
K: AsRef<[u8]> + ConditionalSend,
V: Serialize + ConditionalSend;
async fn get_key<K, V>(&self, key: K) -> Result<Option<V>>
where
K: AsRef<[u8]> + ConditionalSend,
V: DeserializeOwned + ConditionalSend;
async fn unset_key<K>(&mut self, key: K) -> Result<()>
where
K: AsRef<[u8]> + ConditionalSend;
async fn require_key<K, V>(&self, key: K) -> Result<V>
where
K: AsRef<[u8]> + ConditionalSend + Display,
V: DeserializeOwned + ConditionalSend,
{
let required = key.to_string();
match self.get_key(key).await? {
Some(value) => Ok(value),
None => Err(anyhow!("No value found for '{required}'")),
}
}
async fn flush(&self) -> Result<()> {
Ok(())
}
}