Email client, application startup logic and tests

This commit is contained in:
Alphonse Paix
2025-08-24 11:31:03 +02:00
parent 85ab04f254
commit 4389873bf4
14 changed files with 636 additions and 410 deletions

View File

@@ -1,20 +1,46 @@
use crate::routes::*;
use crate::{configuration::Settings, email_client::EmailClient, routes::*};
use axum::{
Router,
extract::MatchedPath,
http::Request,
routing::{get, post},
};
use sqlx::PgPool;
use sqlx::{PgPool, postgres::PgPoolOptions};
use std::sync::Arc;
use tokio::net::TcpListener;
use tower_http::trace::TraceLayer;
use uuid::Uuid;
pub async fn run(listener: TcpListener, connection_pool: PgPool) {
axum::serve(listener, app(connection_pool)).await.unwrap();
pub struct Application {
listener: TcpListener,
router: Router,
}
pub fn app(connection_pool: PgPool) -> Router {
impl Application {
pub async fn build(configuration: Settings) -> Result<Self, std::io::Error> {
let address = format!(
"{}:{}",
configuration.application.host, configuration.application.port
);
let listener = TcpListener::bind(address).await?;
let connection_pool =
PgPoolOptions::new().connect_lazy_with(configuration.database.with_db());
let email_client = EmailClient::new(configuration.email_client);
let router = app(connection_pool, email_client);
Ok(Self { listener, router })
}
pub async fn run_until_stopped(self) -> Result<(), std::io::Error> {
tracing::debug!("listening on {}", self.listener.local_addr().unwrap());
axum::serve(self.listener, self.router).await
}
pub fn address(&self) -> String {
self.listener.local_addr().unwrap().to_string()
}
}
pub fn app(connection_pool: PgPool, email_client: EmailClient) -> Router {
Router::new()
.route("/health_check", get(health_check))
.route("/subscriptions", post(subscribe))
@@ -36,4 +62,5 @@ pub fn app(connection_pool: PgPool) -> Router {
}),
)
.with_state(connection_pool)
.with_state(Arc::new(email_client))
}