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-04 15:27:47 -04:00
|
|
|
pub async fn subscribe_route(
|
|
|
|
form: web::Form<FormData>,
|
|
|
|
db_conn_pool: web::Data<PgPool>,
|
|
|
|
) -> HttpResponse {
|
2024-05-06 00:49:17 -04:00
|
|
|
let request_id = Uuid::new_v4();
|
|
|
|
|
|
|
|
log::info!(
|
|
|
|
"request_id {} - Saving '{}' '{}' as a new subscriber in PostgreSQL",
|
|
|
|
request_id,
|
|
|
|
form.name,
|
|
|
|
form.email
|
|
|
|
);
|
|
|
|
|
2024-05-04 15:27:47 -04:00
|
|
|
match sqlx::query!(
|
|
|
|
r#"
|
|
|
|
INSERT INTO subscriptions (id, email, name, subscribed_at)
|
|
|
|
VALUES ($1, $2, $3, $4)
|
|
|
|
"#,
|
|
|
|
Uuid::new_v4(),
|
|
|
|
form.email,
|
|
|
|
form.name,
|
|
|
|
Utc::now()
|
|
|
|
)
|
|
|
|
.execute(db_conn_pool.get_ref())
|
|
|
|
.await
|
|
|
|
{
|
2024-05-06 00:49:17 -04:00
|
|
|
Ok(_) => {
|
|
|
|
log::info!(
|
|
|
|
"request_id {} - Saved new subscriber details in PostgreSQL",
|
|
|
|
request_id
|
|
|
|
);
|
|
|
|
HttpResponse::Ok().finish()
|
|
|
|
}
|
|
|
|
Err(err) => {
|
|
|
|
log::info!(
|
|
|
|
"request_id {} - Failed to execute query: {:?}",
|
|
|
|
request_id,
|
|
|
|
err
|
|
|
|
);
|
2024-05-04 15:27:47 -04:00
|
|
|
HttpResponse::InternalServerError().finish()
|
|
|
|
}
|
|
|
|
}
|
2024-05-03 15:43:34 -04:00
|
|
|
}
|