Use HTML swap to display success and error messages
This commit is contained in:
@@ -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(
|
||||
|
||||
Reference in New Issue
Block a user