use crate::dao::GarrisonDao;
use async_trait::async_trait;
use limiteron::error::StorageError;
use limiteron::storage::Storage;
use std::sync::Arc;
use super::errors::map_to_storage_err;
pub struct GarrisonDaoStorage {
dao: Arc<dyn GarrisonDao>,
}
impl GarrisonDaoStorage {
pub fn new(dao: Arc<dyn GarrisonDao>) -> Self {
Self { dao }
}
}
#[async_trait]
impl Storage for GarrisonDaoStorage {
async fn get(&self, key: &str) -> Result<Option<String>, StorageError> {
self.dao.get(key).await.map_err(map_to_storage_err)
}
async fn set(&self, key: &str, value: &str, ttl: Option<u64>) -> Result<(), StorageError> {
let ttl_secs = ttl.unwrap_or(0);
self.dao
.set(key, value, ttl_secs)
.await
.map_err(map_to_storage_err)
}
async fn delete(&self, key: &str) -> Result<(), StorageError> {
self.dao.delete(key).await.map_err(map_to_storage_err)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::dao::tests::MockDao;
fn make_dao() -> Arc<dyn GarrisonDao> {
Arc::new(MockDao::new())
}
#[tokio::test]
async fn storage_get_set_delete() {
let storage = GarrisonDaoStorage::new(make_dao());
assert!(storage.get("key1").await.unwrap().is_none());
storage.set("key1", "value1", Some(60)).await.unwrap();
assert_eq!(
storage.get("key1").await.unwrap(),
Some("value1".to_string())
);
storage.delete("key1").await.unwrap();
assert!(storage.get("key1").await.unwrap().is_none());
}
#[tokio::test]
async fn storage_set_ttl_none_is_permanent() {
let storage = GarrisonDaoStorage::new(make_dao());
storage.set("perm", "val", None).await.unwrap();
assert_eq!(storage.get("perm").await.unwrap(), Some("val".to_string()));
}
}