zero2prod_axum/src/routes/subscriptions.rs

127 lines
3.4 KiB
Rust
Raw Normal View History

2024-02-12 10:55:23 +01:00
use crate::domain::SubscriberEmail;
use crate::domain::{NewSubscriber, SubscriberName};
2024-03-05 10:45:09 +01:00
use crate::email_client::EmailClient;
2024-02-21 11:18:44 +01:00
use crate::startup::AppState;
use axum::extract::State;
2024-01-01 21:02:31 +01:00
use axum::routing::post;
use axum::Form;
2023-12-30 22:21:57 +01:00
use axum::Router;
use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
use chrono::Utc;
use serde::Deserialize;
use sqlx::PgPool;
use uuid::Uuid;
#[derive(Debug, Deserialize)]
struct FormData {
email: String,
name: String,
}
impl TryFrom<FormData> for NewSubscriber {
type Error = String;
fn try_from(value: FormData) -> Result<Self, Self::Error> {
let name = SubscriberName::parse(value.name)?;
let email = SubscriberEmail::parse(value.email)?;
Ok(Self { email, name })
}
}
2024-03-05 10:45:09 +01:00
#[tracing::instrument(
name = "Send a confirmation email to a new subscriber",
skip(email_client, new_subscriber, base_url)
2024-03-05 10:45:09 +01:00
)]
pub async fn send_confirmation_email(
email_client: &EmailClient,
new_subscriber: NewSubscriber,
base_url: &str,
2024-03-05 10:45:09 +01:00
) -> Result<(), reqwest::Error> {
2024-04-18 23:00:50 +02:00
let confirmation_link = format!(
"{}/subscriptions/confirm?subscription_token=mytoken",
base_url
);
2024-03-05 10:45:09 +01:00
let plain_body = format!(
"Welcome to our newsletter! Visit {} to confirm your subscription.",
confirmation_link
);
let html_body = format!(
"Welcome to our newsletter!<br />\
Click <a href=\"{}\">here</a> to confirm your subscription.",
confirmation_link
);
email_client
.send_email(new_subscriber.email, "Welcome!", &html_body, &plain_body)
.await
}
2024-03-04 21:49:08 +01:00
// TODO: remove request_id?
2024-02-04 13:48:31 +01:00
#[tracing::instrument(
name = "Adding a new subscriber",
skip(form, db_pool, email_client, base_url),
2024-02-04 13:48:31 +01:00
fields(
request_id = %Uuid::new_v4(),
subscriber_email = %form.email,
subscriber_name = %form.name
)
)]
2024-02-21 11:18:44 +01:00
pub async fn subscribe(
State(AppState {
db_pool,
email_client,
base_url,
2024-02-21 11:18:44 +01:00
}): State<AppState>,
Form(form): Form<FormData>,
) -> Response {
let new_subscriber = match form.try_into() {
Ok(form) => form,
2024-02-12 10:55:23 +01:00
Err(_) => {
return (StatusCode::BAD_REQUEST, "Invalid subscription.").into_response();
2024-02-12 10:55:23 +01:00
}
};
2024-03-04 21:49:08 +01:00
if insert_subscriber(&db_pool, &new_subscriber).await.is_err() {
return (StatusCode::INTERNAL_SERVER_ERROR, "Something went wrong.").into_response();
}
if send_confirmation_email(&email_client, new_subscriber, &base_url.0)
2024-03-04 21:49:08 +01:00
.await
.is_err()
{
return (StatusCode::INTERNAL_SERVER_ERROR, "Something went wrong.").into_response();
2024-02-04 13:48:31 +01:00
}
2024-03-04 21:49:08 +01:00
return (StatusCode::OK,).into_response();
2024-02-04 13:48:31 +01:00
}
#[tracing::instrument(
name = "Saving new subscriber details in the database",
2024-02-21 11:18:44 +01:00
skip(new_subscriber, db_pool)
2024-02-04 13:48:31 +01:00
)]
2024-02-12 10:55:23 +01:00
pub async fn insert_subscriber(
2024-02-21 11:18:44 +01:00
db_pool: &PgPool,
2024-02-12 10:55:23 +01:00
new_subscriber: &NewSubscriber,
) -> Result<(), sqlx::Error> {
let _ = sqlx::query!(
r#"
2024-03-04 21:20:35 +01:00
INSERT INTO subscriptions (id, email, name, subscribed_at, status)
2024-03-09 14:06:47 +01:00
VALUES ($1, $2, $3, $4, 'pending_confirmation')
2024-02-04 13:48:31 +01:00
"#,
Uuid::new_v4(),
2024-02-12 10:55:23 +01:00
new_subscriber.email.as_ref(),
new_subscriber.name.as_ref(),
Utc::now()
)
2024-02-21 11:18:44 +01:00
.execute(db_pool)
2024-01-30 21:43:32 +01:00
.await
2024-02-04 13:48:31 +01:00
.map_err(|e| {
tracing::error!("Failed to execute query: {:?}", e);
e
});
2024-02-04 13:48:31 +01:00
Ok(())
}
2023-12-30 22:21:57 +01:00
2024-04-18 23:00:50 +02:00
pub fn routes_subscriptions() -> Router<AppState> {
Router::new().route("/subscriptions", post(subscribe))
2023-12-30 22:21:57 +01:00
}