1
0
Fork 1
mirror of https://example.com synced 2024-11-22 06:46:40 +09:00

refactor (backend-rs): move connect_to_database to a separate file

This commit is contained in:
naskya 2024-01-27 07:51:35 +09:00
parent 0db57bd423
commit 9374e4ef93
Signed by: naskya
GPG key ID: 712D413B3A9FED5C
2 changed files with 43 additions and 40 deletions

View file

@ -0,0 +1,40 @@
use crate::config::server::SERVER_CONFIG;
use crate::database::NapiDbErrExt;
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(NapiDbErrExt::into)?;
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());
}
}

View file

@ -1,42 +1,5 @@
pub mod connect;
pub mod error;
pub use connect::JsDbConn;
pub use error::NapiDbErrExt;
use crate::config::server::SERVER_CONFIG;
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(NapiDbErrExt::into)?;
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());
}
}