2022-07-16 12:16:54 +00:00
|
|
|
use redis;
|
|
|
|
use redis::Commands;
|
2021-05-02 10:32:03 +00:00
|
|
|
|
2021-12-22 13:46:06 +00:00
|
|
|
use crate::note::now;
|
2021-05-02 10:32:03 +00:00
|
|
|
use crate::note::Note;
|
|
|
|
|
|
|
|
lazy_static! {
|
2022-07-16 12:16:54 +00:00
|
|
|
static ref REDIS_CLIENT: String = std::env::var("REDIS")
|
|
|
|
.unwrap_or("redis://127.0.0.1/".to_string())
|
|
|
|
.parse()
|
|
|
|
.unwrap();
|
2021-05-02 10:32:03 +00:00
|
|
|
}
|
|
|
|
|
2022-07-16 12:16:54 +00:00
|
|
|
fn get_connection() -> Result<redis::Connection, &'static str> {
|
|
|
|
let client =
|
|
|
|
redis::Client::open(REDIS_CLIENT.to_string()).map_err(|_| "Unable to connect to redis")?;
|
|
|
|
client
|
|
|
|
.get_connection()
|
|
|
|
.map_err(|_| "Unable to connect to redis")
|
|
|
|
}
|
|
|
|
|
2023-06-23 08:17:13 +00:00
|
|
|
pub fn can_reach_redis() -> bool {
|
|
|
|
let conn = get_connection();
|
|
|
|
return match conn {
|
|
|
|
Ok(_) => true,
|
|
|
|
Err(_) => false,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2022-07-16 12:16:54 +00:00
|
|
|
pub fn set(id: &String, note: &Note) -> Result<(), &'static str> {
|
2022-03-12 13:07:33 +00:00
|
|
|
let serialized = serde_json::to_string(¬e.clone()).unwrap();
|
2022-07-16 12:16:54 +00:00
|
|
|
let mut conn = get_connection()?;
|
|
|
|
|
|
|
|
conn.set(id, serialized)
|
|
|
|
.map_err(|_| "Unable to set note in redis")?;
|
|
|
|
match note.expiration {
|
|
|
|
Some(e) => {
|
|
|
|
let seconds = e - now();
|
|
|
|
conn.expire(id, seconds as usize)
|
|
|
|
.map_err(|_| "Unable to set expiration on notion")?
|
|
|
|
}
|
|
|
|
None => {}
|
2022-03-12 13:07:33 +00:00
|
|
|
};
|
2022-07-16 12:16:54 +00:00
|
|
|
Ok(())
|
2021-05-02 10:32:03 +00:00
|
|
|
}
|
|
|
|
|
2022-07-16 12:16:54 +00:00
|
|
|
pub fn get(id: &String) -> Result<Option<Note>, &'static str> {
|
|
|
|
let mut conn = get_connection()?;
|
|
|
|
let value: Option<String> = conn.get(id).map_err(|_| "Could not load note in redis")?;
|
2022-03-12 13:07:33 +00:00
|
|
|
match value {
|
2022-07-16 12:16:54 +00:00
|
|
|
None => return Ok(None),
|
2022-03-12 13:07:33 +00:00
|
|
|
Some(s) => {
|
|
|
|
let deserialize: Note = serde_json::from_str(&s).unwrap();
|
2022-07-16 12:16:54 +00:00
|
|
|
return Ok(Some(deserialize));
|
2022-03-12 13:07:33 +00:00
|
|
|
}
|
2021-05-02 10:32:03 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-07-16 12:16:54 +00:00
|
|
|
pub fn del(id: &String) -> Result<(), &'static str> {
|
|
|
|
let mut conn = get_connection()?;
|
|
|
|
conn.del(id).map_err(|_| "Unable to delete note in redis")?;
|
|
|
|
Ok(())
|
2021-05-02 10:32:03 +00:00
|
|
|
}
|