1pub use bb8_redis::bb8::{Pool, PooledConnection};
2pub use bb8_redis::RedisConnectionManager;
3use cal_core::Account;
4use redis::AsyncCommands;
5use std::env;
6
7pub type BB8Pool = Pool<RedisConnectionManager>;
8
9#[derive(Debug)]
10pub struct CacheError {
11 pub msg: String,
12}
13
14impl CacheError {
15 pub fn new_string(s: String) -> CacheError {
16 CacheError { msg: s }
17 }
18}
19
20async fn get_connection(
21 pool: &BB8Pool,
22) -> Result<PooledConnection<RedisConnectionManager>, CacheError> {
23 let con = pool
24 .get()
25 .await
26 .map_err(|e| CacheError::new_string(e.to_string()))?;
27 Ok(con)
28}
29
30async fn get_str(pool: &BB8Pool, key: &str) -> Result<Option<String>, CacheError> {
31 let mut con = get_connection(pool).await?;
32
33 let res: Result<Option<String>, CacheError> = con
34 .get(key)
35 .await
36 .map_err(|e| CacheError::new_string(e.to_string()));
37
38 match res {
39 Ok(r) => match r {
40 None => Ok(None),
41 Some(value) => Ok(Some(value)),
42 },
43 Err(e) => Err(e),
44 }
45}
46
47async fn get_hash(pool: &BB8Pool, key: &str, field: &str) -> Result<Option<String>, CacheError> {
48 let mut con = get_connection(pool).await?;
49
50 let res: Result<Option<String>, CacheError> = con
51 .hget(key, field)
52 .await
53 .map_err(|e| CacheError::new_string(e.to_string()));
54
55 match res {
56 Ok(r) => match r {
57 None => Ok(None),
58 Some(value) => Ok(Some(value)),
59 },
60 Err(e) => Err(e),
61 }
62}
63
64pub async fn get_account_by_ident(
65 pool: &BB8Pool,
66 key: &str,
67) -> Result<Option<Account>, CacheError> {
68 let result = get_hash(pool, "cb:accounts", key).await;
69 match result {
70 Ok(r) => match r {
71 None => Ok(None),
72 Some(value) => get_account_by_id(pool, &value).await,
73 },
74 Err(e) => Err(e),
75 }
76}
77
78pub async fn get_account_by_id(pool: &BB8Pool, key: &str) -> Result<Option<Account>, CacheError> {
79 let _key = format!("cb:account:{}", key);
80 let result = get_str(pool, key).await;
81 match result {
82 Ok(r) => match r {
83 None => Ok(None),
84 Some(value) => {
85 let account: Account = serde_json::from_str(&value).unwrap();
86 Ok(Some(account))
87 }
88 },
89 Err(e) => Err(e),
90 }
91}