feat: prepare email client usage

This commit is contained in:
Sandro Eiler 2024-02-21 11:18:44 +01:00
parent eecab50b55
commit 13db7853bd
12 changed files with 150 additions and 208 deletions

View file

@ -1,5 +1,7 @@
use crate::domain::SubscriberEmail;
use crate::domain::{NewSubscriber, SubscriberName};
use crate::email_client;
use crate::startup::AppState;
use axum::extract::State;
use axum::routing::post;
use axum::Form;
@ -31,21 +33,27 @@ impl TryFrom<FormData> for NewSubscriber {
#[tracing::instrument(
name = "Adding a new subscriber",
skip(form, pool),
skip(form, db_pool, email_client),
fields(
request_id = %Uuid::new_v4(),
subscriber_email = %form.email,
subscriber_name = %form.name
)
)]
pub async fn subscribe(State(pool): State<PgPool>, Form(form): Form<FormData>) -> Response {
pub async fn subscribe(
State(AppState {
db_pool,
email_client,
}): State<AppState>,
Form(form): Form<FormData>,
) -> Response {
let new_subscriber = match form.try_into() {
Ok(form) => form,
Err(_) => {
return (StatusCode::BAD_REQUEST, "Invalid subscription.").into_response();
}
};
match insert_subscriber(&pool, &new_subscriber).await {
match insert_subscriber(&db_pool, &new_subscriber).await {
Ok(_) => {
return (StatusCode::OK,).into_response();
}
@ -57,10 +65,10 @@ pub async fn subscribe(State(pool): State<PgPool>, Form(form): Form<FormData>) -
#[tracing::instrument(
name = "Saving new subscriber details in the database",
skip(new_subscriber, pool)
skip(new_subscriber, db_pool)
)]
pub async fn insert_subscriber(
pool: &PgPool,
db_pool: &PgPool,
new_subscriber: &NewSubscriber,
) -> Result<(), sqlx::Error> {
let _ = sqlx::query!(
@ -75,7 +83,7 @@ pub async fn insert_subscriber(
)
// We use `get_ref` to get an immutable reference to the `PgConnection`
// wrapped by `web::Data`.
.execute(pool)
.execute(db_pool)
.await
.map_err(|e| {
tracing::error!("Failed to execute query: {:?}", e);
@ -84,8 +92,8 @@ pub async fn insert_subscriber(
Ok(())
}
pub fn routes_subscriptions(pool: PgPool) -> Router {
pub fn routes_subscriptions(state: AppState) -> Router {
Router::new()
.route("/subscriptions", post(subscribe))
.with_state(pool)
.with_state(state)
}