1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
use serde::{Deserialize, Serialize};
use serde_json::Value;
#[cfg(feature = "sqlx")]
use sqlx::FromRow;



#[derive(Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "sqlx", derive(FromRow))]
pub struct ConfigEntity {
    pub key: String,
    pub value: Value,
}

impl ConfigEntity {
    pub fn as_string(&self) -> String {
        self.value
            .as_str()
            .expect("value is not a string")
            .to_string()
    }

    pub fn as_bool(&self) -> bool {
        self.value.as_bool().expect("value is not a boolean")
    }

    pub fn as_int(&self) -> i64 {
        self.value.as_i64().expect("value is not a number")
    }
}

#[cfg(feature = "sqlx")]
impl ConfigEntity {
    pub async fn get_by_key(conn: &mut sqlx::MySqlConnection, key: &str) -> Result<Self, Error> {
        sqlx::query_as("SELECT * FROM config WHERE `key` = ?")
            .bind(key)
            .fetch_one(conn)
            .await
            .map_err(Error::SQLX)
    }

    pub async fn collect(conn: &mut sqlx::MySqlConnection) -> Result<Vec<Self>, Error> {
        sqlx::query_as("SELECT * FROM config")
            .fetch_all(conn)
            .await
            .map_err(Error::SQLX)
    }
}