2024-05-03 15:43:34 -04:00
|
|
|
use actix_web::{web, HttpResponse};
|
2024-05-04 15:27:47 -04:00
|
|
|
use chrono::Utc;
|
|
|
|
use sqlx::PgPool;
|
|
|
|
use uuid::Uuid;
|
2024-05-03 15:43:34 -04:00
|
|
|
|
|
|
|
#[derive(serde::Deserialize)]
|
|
|
|
pub struct FormData {
|
|
|
|
email: String,
|
|
|
|
name: String,
|
|
|
|
}
|
|
|
|
|
2024-05-08 17:27:05 -04:00
|
|
|
#[tracing::instrument(
|
|
|
|
name = "Adding a new subscriber",
|
|
|
|
// functions args isn't really relevant to the span
|
|
|
|
skip(form, db_conn_pool),
|
|
|
|
fields(
|
|
|
|
request_id = %Uuid::new_v4(),
|
|
|
|
subscriber_email = %form.email,
|
|
|
|
subscriber_name = %form.name
|
|
|
|
)
|
|
|
|
)]
|
2024-05-04 15:27:47 -04:00
|
|
|
pub async fn subscribe_route(
|
|
|
|
form: web::Form<FormData>,
|
|
|
|
db_conn_pool: web::Data<PgPool>,
|
|
|
|
) -> HttpResponse {
|
2024-05-08 17:27:05 -04:00
|
|
|
match insert_subscriber(&db_conn_pool, &form).await {
|
|
|
|
Ok(_) => HttpResponse::Ok().finish(),
|
|
|
|
Err(_) => HttpResponse::InternalServerError().finish(),
|
|
|
|
}
|
|
|
|
}
|
2024-05-07 16:10:09 -04:00
|
|
|
|
2024-05-08 17:27:05 -04:00
|
|
|
#[tracing::instrument(
|
|
|
|
name = "Saving new subscriber details in the database",
|
|
|
|
skip(form, pool)
|
|
|
|
)]
|
|
|
|
pub async fn insert_subscriber(pool: &PgPool, form: &FormData) -> Result<(), sqlx::Error> {
|
|
|
|
sqlx::query!(
|
2024-05-04 15:27:47 -04:00
|
|
|
r#"
|
|
|
|
INSERT INTO subscriptions (id, email, name, subscribed_at)
|
|
|
|
VALUES ($1, $2, $3, $4)
|
2024-05-08 17:27:05 -04:00
|
|
|
"#,
|
2024-05-04 15:27:47 -04:00
|
|
|
Uuid::new_v4(),
|
|
|
|
form.email,
|
|
|
|
form.name,
|
|
|
|
Utc::now()
|
|
|
|
)
|
2024-05-08 17:27:05 -04:00
|
|
|
.execute(pool)
|
2024-05-04 15:27:47 -04:00
|
|
|
.await
|
2024-05-08 17:27:05 -04:00
|
|
|
.map_err(|e| {
|
|
|
|
tracing::error!("Failed to execute query: {:?}", e);
|
|
|
|
e
|
|
|
|
// Using the `?` operator to return early
|
|
|
|
// if the function failed, returning a sqlx::Error
|
|
|
|
// We will talk about error handling in depth later!
|
|
|
|
})?;
|
|
|
|
Ok(())
|
2024-05-03 15:43:34 -04:00
|
|
|
}
|