Skip to content

Commit

Permalink
refactor(subscriptions): separation of concerns
Browse files Browse the repository at this point in the history
  • Loading branch information
Yag000 committed Aug 30, 2023
1 parent d13dee8 commit 3a34a39
Showing 1 changed file with 25 additions and 20 deletions.
45 changes: 25 additions & 20 deletions src/routes/subscriptions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,28 @@ pub struct FormData {
name: String,
}

pub async fn subscribe(form: web::Form<FormData>, pool: web::Data<PgPool>) -> 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<FormData>, pool: web::Data<PgPool>) -> 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)
Expand All @@ -32,16 +42,11 @@ pub async fn subscribe(form: web::Form<FormData>, pool: web::Data<PgPool>) -> 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(())
}

0 comments on commit 3a34a39

Please sign in to comment.