use crate::config::AppConfig;
use crate::db;
use axum::Router;
use sea_orm::DatabaseConnection;
use sea_orm_migration::MigratorTrait;
#[derive(Clone)]
pub struct FrameworkContext {
pub config: AppConfig,
pub db: DatabaseConnection,
}
pub async fn run<F>(build_router: F) -> anyhow::Result<()>
where
F: FnOnce(&FrameworkContext) -> Router,
{
let config = AppConfig::from_env()?;
let db = db::connect_db(&config).await?;
let ctx = FrameworkContext {
config: config.clone(),
db,
};
let app = build_router(&ctx);
let bind_addr = config.bind_address();
tracing::info!("Starting server on {}", bind_addr);
let listener = tokio::net::TcpListener::bind(&bind_addr).await?;
axum::serve(listener, app).await?;
Ok(())
}
pub async fn run_with_migrator<M, F>(build_router: F, run_migrations: bool) -> anyhow::Result<()>
where
M: MigratorTrait,
F: FnOnce(&FrameworkContext) -> Router,
{
let config = AppConfig::from_env()?;
let db = db::connect_db(&config).await?;
if run_migrations {
tracing::info!("Running database migrations...");
M::up(&db, None).await?;
tracing::info!("Migrations completed successfully");
}
let ctx = FrameworkContext {
config: config.clone(),
db,
};
let app = build_router(&ctx);
let bind_addr = config.bind_address();
tracing::info!("Starting server on {}", bind_addr);
let listener = tokio::net::TcpListener::bind(&bind_addr).await?;
axum::serve(listener, app).await?;
Ok(())
}