Skip to main content

horfimbor_eventsource/cache_db/
redis.rs

1//! Redis implementation of the `CacheDb`
2
3use std::marker::PhantomData;
4
5use redis::{Client, Commands};
6
7use crate::Dto;
8use crate::cache_db::{CacheDb, DbError};
9use crate::model_key::ModelKey;
10
11/// The `StateDb` is a container for the Type system and a db connection
12#[derive(Clone)]
13pub struct StateDb<S> {
14    client: Client,
15    state: PhantomData<S>,
16}
17
18impl<S> StateDb<S> {
19    /// simple constructor
20    #[must_use]
21    pub const fn new(client: Client) -> Self {
22        Self {
23            client,
24            state: PhantomData,
25        }
26    }
27}
28
29impl<S> CacheDb<S> for StateDb<S>
30where
31    S: Dto,
32{
33    fn get_from_db(&self, prefix: Option<&str>, key: &ModelKey) -> Result<Option<String>, DbError> {
34        let mut connection = self
35            .client
36            .get_connection()
37            .map_err(|e| DbError::Disconnect(e.to_string()))?;
38
39        let key = prefix.map_or_else(|| key.format(), |prefix| format!("{prefix}-{key}"));
40
41        let data: Option<String> = connection
42            .get(key)
43            .map_err(|e| DbError::Internal(e.to_string()))?;
44
45        Ok(data)
46    }
47
48    fn set_in_db(
49        &self,
50        prefix: Option<&str>,
51        key: &ModelKey,
52        state: String,
53    ) -> Result<(), DbError> {
54        let mut connection = self
55            .client
56            .get_connection()
57            .map_err(|e| DbError::Disconnect(e.to_string()))?;
58
59        let key = prefix.map_or_else(|| key.format(), |prefix| format!("{prefix}-{key}"));
60
61        connection
62            .set::<_, _, ()>(key, state)
63            .map_err(|err| DbError::Internal(err.to_string()))?;
64
65        Ok(())
66    }
67}