2024-11-22 13:13:04 +08:00
|
|
|
mod auth;
|
2024-11-19 00:20:31 +08:00
|
|
|
mod config;
|
|
|
|
mod database;
|
2024-11-22 13:13:04 +08:00
|
|
|
mod manage;
|
2024-11-20 19:53:18 +08:00
|
|
|
mod routes;
|
2024-11-22 13:13:04 +08:00
|
|
|
mod utils;
|
2024-11-19 00:20:31 +08:00
|
|
|
use database::relational;
|
2024-11-22 13:13:04 +08:00
|
|
|
use rocket::launch;
|
2024-11-19 00:20:31 +08:00
|
|
|
use std::sync::Arc;
|
|
|
|
use tokio::sync::Mutex;
|
2024-11-22 13:13:04 +08:00
|
|
|
use utils::{AppResult, CustomError, CustomResult};
|
2024-11-20 19:53:18 +08:00
|
|
|
|
|
|
|
struct AppState {
|
|
|
|
db: Arc<Mutex<Option<relational::Database>>>,
|
|
|
|
configure: Arc<Mutex<config::Config>>,
|
2024-11-09 00:05:18 +08:00
|
|
|
}
|
2024-11-11 19:31:40 +08:00
|
|
|
|
2024-11-20 19:53:18 +08:00
|
|
|
impl AppState {
|
2024-11-22 13:13:04 +08:00
|
|
|
async fn get_sql(&self) -> CustomResult<relational::Database> {
|
2024-11-20 19:53:18 +08:00
|
|
|
self.db
|
|
|
|
.lock()
|
|
|
|
.await
|
|
|
|
.clone()
|
2024-11-21 19:07:42 +08:00
|
|
|
.ok_or_else(|| CustomError::from_str("Database not initialized"))
|
2024-11-20 19:53:18 +08:00
|
|
|
}
|
|
|
|
|
2024-11-22 13:13:04 +08:00
|
|
|
async fn link_sql(&self, config: &config::SqlConfig) -> CustomResult<()> {
|
|
|
|
let database = relational::Database::link(config).await?;
|
2024-11-20 19:53:18 +08:00
|
|
|
*self.db.lock().await = Some(database);
|
|
|
|
Ok(())
|
|
|
|
}
|
2024-11-18 01:09:28 +08:00
|
|
|
}
|
|
|
|
|
2024-11-09 00:05:18 +08:00
|
|
|
#[launch]
|
|
|
|
async fn rocket() -> _ {
|
2024-11-19 00:20:31 +08:00
|
|
|
let config = config::Config::read().expect("Failed to read config");
|
2024-11-22 13:13:04 +08:00
|
|
|
|
2024-11-20 19:53:18 +08:00
|
|
|
let state = AppState {
|
|
|
|
db: Arc::new(Mutex::new(None)),
|
|
|
|
configure: Arc::new(Mutex::new(config.clone())),
|
|
|
|
};
|
|
|
|
|
|
|
|
let mut rocket_builder = rocket::build().manage(state);
|
2024-11-18 19:14:37 +08:00
|
|
|
|
|
|
|
if config.info.install {
|
2024-11-20 19:53:18 +08:00
|
|
|
if let Some(state) = rocket_builder.state::<AppState>() {
|
2024-11-22 13:13:04 +08:00
|
|
|
state
|
|
|
|
.link_sql(&config.sql_config)
|
2024-11-20 19:53:18 +08:00
|
|
|
.await
|
|
|
|
.expect("Failed to connect to database");
|
|
|
|
}
|
2024-11-22 13:13:04 +08:00
|
|
|
} else {
|
|
|
|
rocket_builder = rocket_builder.mount("/", rocket::routes![routes::intsall::install]);
|
2024-11-18 19:14:37 +08:00
|
|
|
}
|
2024-11-20 19:53:18 +08:00
|
|
|
|
2024-11-22 13:13:04 +08:00
|
|
|
rocket_builder = rocket_builder.mount("/auth/token", routes::jwt_routes());
|
2024-11-20 19:53:18 +08:00
|
|
|
|
|
|
|
rocket_builder
|
2024-11-21 01:04:59 +08:00
|
|
|
}
|