zero2prod_axum/src/routes/subscriptions.rs

67 lines
1.6 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,
}
2024-02-04 13:48:31 +01:00
#[tracing::instrument(
name = "Adding a new subscriber",
skip(form, pool),
fields(
request_id = %Uuid::new_v4(),
subscriber_email = %form.email,
subscriber_name = %form.name
)
)]
pub async fn subscribe(State(pool): State<PgPool>, Form(form): Form<FormData>) {
match insert_subscriber(&pool, &form).await {
Ok(_) => {
tracing::info!("Subscriber added to the database");
}
Err(_) => {
tracing::error!("Failed to add subscriber to the database");
}
}
}
#[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!(
r#"
2024-02-04 13:48:31 +01:00
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`.
2024-02-04 13:48:31 +01:00
.execute(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
})?;
Ok(())
}
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
}