use std::sync::Arc;
use super::{Store, StoreError};
#[derive(Debug)]
pub struct InStoreCounter {
pub store: Arc<dyn Store>,
pub key: String,
}
impl InStoreCounter {
pub fn new(store: Arc<dyn Store>, key: String) -> Self {
Self { store, key }
}
pub async fn get(&self) -> Result<usize, StoreError> {
self.store
.get(&self.key)
.await
.map_err(|_| StoreError::GetError)?
.unwrap_or("0".to_string())
.parse::<usize>()
.map_err(StoreError::Parse)
}
pub async fn set(&self, count: usize) -> Result<(), StoreError> {
self.store.set(&self.key, &count.to_string()).await?;
Ok(())
}
pub async fn increment(&self) -> Result<usize, StoreError> {
let current_count = self.get().await?;
let new_count = current_count + 1;
self.set(new_count).await?;
Ok(new_count)
}
}