ft_sdk/session/
session_data.rs

1/// Store and retrieve session data
2pub struct SessionData {
3    session_id: String,
4    data: std::collections::HashMap<String, serde_json::Value>,
5}
6
7impl SessionData {
8    pub(crate) fn new(
9        id: &str,
10        data: std::collections::HashMap<String, serde_json::Value>,
11    ) -> SessionData {
12        SessionData {
13            session_id: id.to_string(),
14            data,
15        }
16    }
17
18    /// Get the value of a key in the session data.
19    pub fn get_key<S: AsRef<str>, V: serde::de::DeserializeOwned>(&self, k: S) -> Option<V> {
20        self.data
21            .get(k.as_ref())
22            .cloned()
23            .and_then(|v| serde_json::from_value(v).ok())
24    }
25
26    /// Temporarly store a key in the session data.
27    /// Use [SessionData::persist] to save the data back to the database
28    pub fn set<S: AsRef<str>, V: serde::Serialize>(
29        &mut self,
30        k: S,
31        v: V,
32    ) -> Result<(), serde_json::Error> {
33        let value = serde_json::to_value(v)?;
34        self.data.insert(k.as_ref().to_string(), value);
35
36        Ok(())
37    }
38
39    /// Save the session data to the database
40    pub fn persist(&self, conn: &mut ft_sdk::Connection) -> Result<(), diesel::result::Error> {
41        use diesel::prelude::*;
42        use ft_sdk::schema::fastn_session;
43
44        let data = serde_json::to_string(&self.data).unwrap();
45
46        diesel::update(fastn_session::table.filter(fastn_session::id.eq(self.session_id.as_str())))
47            .set(fastn_session::data.eq(data))
48            .execute(conn)?;
49
50        Ok(())
51    }
52}