diff --git a/src/routes/subscriptions.rs b/src/routes/subscriptions.rs index 25f8f95..b06aecf 100644 --- a/src/routes/subscriptions.rs +++ b/src/routes/subscriptions.rs @@ -11,18 +11,28 @@ pub struct FormData { name: String, } -pub async fn subscribe(form: web::Form, pool: web::Data) -> HttpResponse { - let request_id = Uuid::new_v4(); - let request_span = tracing::info_span!( - " Adding a new subscriber", - %request_id, +#[tracing::instrument( + name = "Adding a new subscriber", + skip(form, pool), + fields( + request_id = %Uuid::new_v4(), subscriber_email = %form.email, subscriber_name = %form.name, - ); - let _request_span_guard = request_span.enter(); + ) +)] +pub async fn subscribe(form: web::Form, pool: web::Data) -> HttpResponse { + match insert_subscriber(&form, &pool).await { + Ok(_) => HttpResponse::Ok().finish(), + Err(_) => HttpResponse::InternalServerError().finish(), + } +} - let query_span = tracing::info_span!("Saving new subscriber details in the database"); - match sqlx::query!( +#[tracing::instrument( + name = "Saving new subscriber details in the database", + skip(form, pool) +)] +pub async fn insert_subscriber(form: &FormData, pool: &PgPool) -> Result<(), sqlx::Error> { + sqlx::query!( r#" INSERT INTO subscriptions (id, email, name, subscribed_at) VALUES ($1, $2, $3, $4) @@ -32,16 +42,11 @@ pub async fn subscribe(form: web::Form, pool: web::Data) -> Ht form.name, Utc::now() ) - // We use `get_ref` to get an immutable reference to the `PgConnection` - // wrapped by `web::Data`. - .execute(pool.get_ref()) - .instrument(query_span) + .execute(pool) .await - { - Ok(_) => HttpResponse::Ok().finish(), - Err(e) => { - tracing::error!("Failed to execute query: {:?}", e); - HttpResponse::InternalServerError().finish() - } - } + .map_err(|e| { + tracing::error!("Failed to execute query: {:?}", e); + e + })?; + Ok(()) }