Skip to main content

redispatch/
lib.rs

1use redis::aio::{Connection, ConnectionLike};
2use redis::{cmd, AsyncCommands, FromRedisValue, RedisFuture, ToRedisArgs};
3use serde::{Serialize, de::DeserializeOwned};
4
5#[async_trait::async_trait]
6trait JsonSerdeCommands: AsyncCommands {
7    async fn get<'a, K, RV>(&'a mut self, key: K) -> Option<RV>
8    where
9        K: Serialize + Send + Sync + 'a,
10        RV: DeserializeOwned,
11    {
12        let data: Option<Vec<u8>> = AsyncCommands::get(self, serde_json::to_string(&key).unwrap())
13            .await
14            .unwrap();
15        if let Some(data) = data {
16            Some(serde_json::from_slice(data.as_slice()).unwrap())
17        } else {
18            None
19        }
20    }
21
22    async fn set<'a, K, V, RV>(&'a mut self, key: K, value: V) -> ()
23    where
24        K: Serialize + Send + Sync + 'a,
25        V: Serialize + Send + Sync + 'a,
26    {
27        AsyncCommands::set::<_, _, ()>(
28            self,
29            serde_json::to_string(&key).unwrap(),
30            serde_json::to_string(&value).unwrap(),
31        )
32        .await
33        .unwrap();
34    }
35}