]> Untitled Git - lemmy.git/blob - crates/db_queries/src/source/secret.rs
eac0d7eb4905b39e5897d042ddcc78b9fdad9b2a
[lemmy.git] / crates / db_queries / src / source / secret.rs
1 use diesel::{result::Error, *};
2 use lemmy_db_schema::source::secret::Secret;
3 use lemmy_utils::settings::structs::Settings;
4 use std::sync::RwLock;
5
6 use crate::get_database_url_from_env;
7
8 lazy_static! {
9   static ref SECRET: RwLock<Secret> = RwLock::new(init().expect("Failed to load secrets from DB."));
10 }
11
12 pub trait SecretSingleton {
13   fn get() -> Secret;
14 }
15
16 impl SecretSingleton for Secret {
17   /// Returns the Secret as a struct
18   fn get() -> Self {
19     SECRET.read().expect("read secrets").to_owned()
20   }
21 }
22
23 /// Reads the secrets from the DB
24 fn init() -> Result<Secret, Error> {
25   let db_url = match get_database_url_from_env() {
26     Ok(url) => url,
27     Err(_) => Settings::get().get_database_url(),
28   };
29
30   let conn = PgConnection::establish(&db_url).expect("Couldn't get DB connection for Secrets.");
31   read_secrets(&conn)
32 }
33
34 fn read_secrets(conn: &PgConnection) -> Result<Secret, Error> {
35   use lemmy_db_schema::schema::secret::dsl::*;
36   secret.first::<Secret>(conn)
37 }