Skip to content

Commit

Permalink
impl for getting env values
Browse files Browse the repository at this point in the history
  • Loading branch information
Pugma committed Sep 27, 2024
1 parent 1915efb commit 0fe08c6
Showing 1 changed file with 35 additions and 8 deletions.
43 changes: 35 additions & 8 deletions server/app/src/repo.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::{env, sync::LazyLock};

use anyhow::{Ok, Result};
use sqlx::{
mysql::{MySqlConnectOptions, MySqlPoolOptions},
Expand All @@ -17,15 +19,40 @@ pub struct Repository {

impl Repository {
pub async fn setup() -> Result<Self> {
let options = MySqlConnectOptions::new()
.host("host")
.port(1111)
.username("username")
.password("password")
.database("database");

let pool = MySqlPoolOptions::new().connect_with(options).await?;
let pool = MySqlPoolOptions::new()
.connect_with(DB_CONFIG.options())
.await?;

Ok(Self { pool })
}
}

struct Config {
db_database: String,
db_host: String,
db_password: String,
db_port: u16,
db_username: String,
}

impl Config {
fn options(&self) -> MySqlConnectOptions {
MySqlConnectOptions::new()
.database(&self.db_database)
.host(&self.db_host)
.password(&self.db_password)
.port(self.db_port)
.username(&self.db_username)
}
}

static DB_CONFIG: LazyLock<Config> = LazyLock::new(|| Config {
db_database: env::var("DB_DATABASE").expect("Failed to get DB_DATABASE !"),
db_host: env::var("DB_HOST").expect("Failed to get DB_HOST !"),
db_password: env::var("DB_PASSWORD").expect("Failed to get DB_PASSWORD !"),
db_port: env::var("DB_PORT")
.expect("Failed to get DB_PORT !")
.parse()
.expect("Failed to parse String to u16"),
db_username: env::var("DB_USERNAME").expect("Failed to get DB_USERNAME !"),
});

0 comments on commit 0fe08c6

Please sign in to comment.