From 0fe08c6f5ed07363c8cff39773ff2b12abf6aab3 Mon Sep 17 00:00:00 2001 From: Pugma Date: Sat, 28 Sep 2024 00:31:33 +0900 Subject: [PATCH] impl for getting env values --- server/app/src/repo.rs | 43 ++++++++++++++++++++++++++++++++++-------- 1 file changed, 35 insertions(+), 8 deletions(-) diff --git a/server/app/src/repo.rs b/server/app/src/repo.rs index 3268fc2..e37cecd 100644 --- a/server/app/src/repo.rs +++ b/server/app/src/repo.rs @@ -1,3 +1,5 @@ +use std::{env, sync::LazyLock}; + use anyhow::{Ok, Result}; use sqlx::{ mysql::{MySqlConnectOptions, MySqlPoolOptions}, @@ -17,15 +19,40 @@ pub struct Repository { impl Repository { pub async fn setup() -> Result { - 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 = 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 !"), +});