Refactor AppState and update database connection handling; integrate SettingsService

This commit is contained in:
GW_MC
2025-12-02 16:56:01 +08:00
parent fae951c902
commit f71cf370cd
2 changed files with 31 additions and 12 deletions

View File

@@ -1,14 +1,23 @@
mod configs;
mod errors;
mod middlewares;
mod routes;
mod services;
mod tasks;
use std::sync::Arc;
use axum::Router;
use database::{ConnectOptions, get_connection};
use database::get_connection;
use sea_orm::ConnectOptions;
use tracing::{debug, info};
use tracing_subscriber::fmt::format::{DefaultFields, Format};
use crate::configs::{ProgramSettings, get_program_settings, logging::LoggingSettings};
use crate::{
configs::{ProgramSettings, get_program_settings, logging::LoggingSettings},
routes::{AppService, AppState},
services::settings::SettingsService,
};
#[tokio::main]
async fn main() {
@@ -53,18 +62,17 @@ async fn main() {
options.max_connections(settings.database.max_connections);
};
let db_connection = get_connection(&settings.database.url, Some(db_options))
.await
.expect("Failed to establish database connection");
let db_connection = Arc::new(
get_connection(&settings.database.url, Some(db_options))
.await
.expect("Failed to establish database connection"),
);
info!("Database connection established.");
// build the axum app and run the server...
info!("Starting application...");
let app: Router = routes::get_root_router(routes::AppState {
database_connection: db_connection,
service: std::sync::Arc::new(routes::AppService {}),
});
let app: Router = routes::get_root_router(Arc::new(get_app_state(&db_connection)));
let address = format!("{}:{}", settings.server.address, settings.server.port);
info!("Starting server at http://{}", address);
@@ -101,6 +109,15 @@ fn get_global_tracing_subscriber_builder(
}
}
fn get_app_state(db_connection: &Arc<sea_orm::DatabaseConnection>) -> AppState {
AppState {
database_connection: db_connection.clone(),
service: Arc::new(AppService {
settings: Arc::new(SettingsService::new(db_connection.clone())),
}),
}
}
// A small wrapper that holds a boxed `FormatTime` trait object and itself
// implements `FormatTime`, allowing us to use it as a concrete type with
// `builder.with_timer` while still picking the concrete timer implementation