SquidSpirit e72f5a5a8e
All checks were successful
Frontend CI / build (push) Successful in 1m29s
BLOG-43 feat: connect to database
2025-05-07 03:06:43 +08:00

61 lines
1.5 KiB
Rust

use actix_web::{
App, Error, HttpServer,
body::MessageBody,
dev::{ServiceFactory, ServiceRequest, ServiceResponse},
web,
};
use post::framework::web::post_web_routes::configure_post_routes;
use server::use_cases::UseCases;
use sqlx::{Pool, Postgres, postgres::PgPoolOptions};
use std::{env, sync::Arc};
#[actix_web::main]
async fn main() -> std::io::Result<()> {
dotenv::dotenv().ok();
env_logger::init();
let db_pool = init_database().await;
HttpServer::new(move || create_app(db_pool.clone()))
.bind(("127.0.0.1", 8080))?
.run()
.await
}
async fn init_database() -> Arc<Pool<Postgres>> {
let database_url = env::var("DATABASE_URL")
.unwrap_or_else(|_| "postgres://postgres@localhost:5432/postgres".to_string());
let db_pool = PgPoolOptions::new()
.max_connections(5)
.connect(&database_url)
.await
.expect("Failed to create database connection pool");
sqlx::migrate!("../migrations")
.run(&db_pool)
.await
.expect("Failed to run database migrations");
Arc::new(db_pool)
}
fn create_app(
db_pool: Arc<Pool<Postgres>>,
) -> App<
impl ServiceFactory<
ServiceRequest,
Response = ServiceResponse<impl MessageBody>,
Config = (),
InitError = (),
Error = Error,
>,
> {
let use_cases = UseCases::new(db_pool.clone());
App::new()
.app_data(web::Data::new(db_pool))
.app_data(web::Data::new(use_cases.get_all_post_info_use_case))
.configure(configure_post_routes)
}