firefish/packages/backend-rs/src/database.rs
sup39 8fa30c7a15
refactor (backend-rs)
Co-authored-by: naskya <m@naskya.net>
2024-02-20 00:21:50 +09:00

38 lines
887 B
Rust

use crate::config::server::SERVER_CONFIG;
use crate::prelude::to_napi_error;
use sea_orm::{Database, DbConn};
use urlencoding::encode;
#[napi_derive::napi]
pub struct JsDbConn {
inner: DbConn,
}
impl JsDbConn {
pub fn inner(&self) -> &DbConn {
&self.inner
}
}
#[napi_derive::napi]
pub async fn connect_to_database() -> napi::Result<JsDbConn> {
let conn_uri = format!(
"postgres://{}:{}@{}:{}/{}",
SERVER_CONFIG.db.user,
encode(&SERVER_CONFIG.db.pass),
SERVER_CONFIG.db.host,
SERVER_CONFIG.db.port,
SERVER_CONFIG.db.db,
);
let conn = Database::connect(conn_uri).await.map_err(to_napi_error)?;
Ok(JsDbConn { inner: conn })
}
#[cfg(test)]
mod unit_test {
use super::connect_to_database;
#[tokio::test]
async fn connect_test() {
assert!(connect_to_database().await.is_ok());
}
}