Skip to content

Commit

Permalink
Accept JSON db params
Browse files Browse the repository at this point in the history
  • Loading branch information
kacperzuk-neti committed Sep 17, 2024
1 parent 55df920 commit 769a6b5
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 9 deletions.
15 changes: 6 additions & 9 deletions fplus-database/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
pub mod config;
pub mod database;
pub mod models;
mod types;

use crate::config::get_env_or_throw;
use once_cell::sync::Lazy;
use sea_orm::{Database, DatabaseConnection, DbErr};
use std::sync::Mutex;
use types::DbConnectParams;

/**
* The global database connection
Expand All @@ -30,15 +32,10 @@ pub fn init() {
*/
pub async fn setup() -> Result<(), DbErr> {
let database_url = std::env::var("DB_URL").unwrap_or_else(|_| {
format!(
"postgres://{}:{}@{}:{}/{}?{}",
get_env_or_throw("DB_USER"),
urlencoding::encode(&get_env_or_throw("DB_PASS")),
get_env_or_throw("DB_HOST"),
std::env::var("DB_PORT").unwrap_or("5432".into()),
get_env_or_throw("DB_NAME"),
std::env::var("DB_OPTIONS").unwrap_or_default()
)
let params: DbConnectParams =
serde_json::from_str(&get_env_or_throw("DB_CONNECT_PARAMS_JSON"))
.expect("Invalid JSON in DB_CONNECT_PARAMS_JSON");
params.to_url()
});
let db_conn = Database::connect(&database_url).await?;
let mut db_conn_global = DB_CONN.lock().unwrap();
Expand Down
26 changes: 26 additions & 0 deletions fplus-database/src/types.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
use serde::Deserialize;

#[derive(Deserialize)]
pub(super) struct DbConnectParams {
password: String,
dbname: String,
engine: String,
port: u16,
host: String,
username: String,
}

impl DbConnectParams {
pub fn to_url(&self) -> String {
format!(
"{}://{}:{}@{}:{}/{}?{}",
self.engine,
self.username,
urlencoding::encode(&self.password),
self.host,
self.port,
self.dbname,
std::env::var("DB_OPTIONS").unwrap_or_default(),
)
}
}

0 comments on commit 769a6b5

Please sign in to comment.