cryptgeon/backend/src/store.rs

56 lines
1.6 KiB
Rust
Raw Normal View History

use redis;
use redis::Commands;
2021-05-02 12:32:03 +02:00
2021-12-22 14:46:06 +01:00
use crate::note::now;
2021-05-02 12:32:03 +02:00
use crate::note::Note;
lazy_static! {
static ref REDIS_CLIENT: String = std::env::var("REDIS")
.unwrap_or("redis://127.0.0.1/".to_string())
.parse()
.unwrap();
2021-05-02 12:32:03 +02: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")
}
pub fn set(id: &String, note: &Note) -> Result<(), &'static str> {
2022-03-12 14:07:33 +01:00
let serialized = serde_json::to_string(&note.clone()).unwrap();
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 14:07:33 +01:00
};
Ok(())
2021-05-02 12:32:03 +02: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 14:07:33 +01:00
match value {
None => return Ok(None),
2022-03-12 14:07:33 +01:00
Some(s) => {
let deserialize: Note = serde_json::from_str(&s).unwrap();
return Ok(Some(deserialize));
2022-03-12 14:07:33 +01:00
}
2021-05-02 12:32:03 +02: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 12:32:03 +02:00
}