zero2prod_axum/src/routes/subscriptions.rs

64 lines
1.5 KiB
Rust
Raw Normal View History

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 chrono::Utc;
use serde::Deserialize;
use sqlx::PgPool;
use uuid::Uuid;
#[derive(Debug, Deserialize)]
struct FormData {
email: String,
name: String,
}
async fn subscribe(State(pool): State<PgPool>, Form(form): Form<FormData>) {
2024-01-30 21:43:32 +01:00
let request_id = Uuid::new_v4();
tracing::info!(
"request_id {} - Adding '{}' '{}' as a new subscriber.",
request_id,
form.email,
form.name
);
tracing::info!(
"request_id {} - Saving new subscriber details in the database",
request_id
);
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()
)
// We use `get_ref` to get an immutable reference to the `PgConnection`
// wrapped by `web::Data`.
.execute(&pool)
2024-01-30 21:43:32 +01:00
.await
{
Ok(_) => {
tracing::info!(
"request_id {} - New subscriber details have been saved",
request_id
);
}
Err(e) => {
tracing::error!(
"request_id {} - Failed to execute query: {:?}",
request_id,
e
);
}
};
}
2023-12-30 22:21:57 +01:00
pub fn routes_subscriptions(pool: PgPool) -> Router {
Router::new()
.route("/subscriptions", post(subscribe))
.with_state(pool)
2023-12-30 22:21:57 +01:00
}