Use HTML swap to display success and error messages

This commit is contained in:
Alphonse Paix
2025-09-17 03:40:23 +02:00
parent 88dad022ce
commit 2d336ed000
18 changed files with 134 additions and 232 deletions

View File

@@ -2,15 +2,16 @@ use crate::{
domain::{NewSubscriber, SubscriberEmail},
email_client::EmailClient,
startup::AppState,
templates::{ErrorTemplate, SuccessTemplate},
};
use anyhow::Context;
use askama::Template;
use axum::{
Form, Json,
extract::State,
http::StatusCode,
response::{IntoResponse, Redirect, Response},
response::{Html, IntoResponse, Response},
};
use axum_messages::Messages;
use chrono::Utc;
use rand::{Rng, distr::Alphanumeric};
use serde::Deserialize;
@@ -72,20 +73,22 @@ impl IntoResponse for SubscribeError {
}),
)
.into_response(),
SubscribeError::ValidationError(_) => Redirect::to("/").into_response(),
SubscribeError::ValidationError(e) => {
let template = ErrorTemplate { error_message: e };
Html(template.render().unwrap()).into_response()
}
}
}
}
#[tracing::instrument(
name = "Adding a new subscriber",
skip(messages, connection_pool, email_client, base_url, form),
skip(connection_pool, email_client, base_url, form),
fields(
subscriber_email = %form.email,
)
)]
pub async fn subscribe(
messages: Messages,
State(AppState {
connection_pool,
email_client,
@@ -97,7 +100,6 @@ pub async fn subscribe(
let new_subscriber = match form.try_into() {
Ok(new_sub) => new_sub,
Err(e) => {
messages.error(&e);
return Err(SubscribeError::ValidationError(e));
}
};
@@ -124,8 +126,10 @@ pub async fn subscribe(
.commit()
.await
.context("Failed to commit the database transaction to store a new subscriber.")?;
messages.success("A confirmation email has been sent.");
Ok(Redirect::to("/").into_response())
let template = SuccessTemplate {
success_message: "A confirmation email has been sent.".to_string(),
};
Ok(Html(template.render().unwrap()).into_response())
}
#[tracing::instrument(