mirror of
https://github.com/kristoferssolo/zero2prod.git
synced 2025-10-21 20:10:40 +00:00
refactor(subscibtions): separate subscribe function
This commit is contained in:
parent
28db61dc51
commit
f814772599
@ -2,7 +2,7 @@ use axum::{extract::State, http::StatusCode, response::IntoResponse, Form};
|
|||||||
use chrono::Utc;
|
use chrono::Utc;
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use sqlx::PgPool;
|
use sqlx::PgPool;
|
||||||
use tracing::{error, info_span, Instrument};
|
use tracing::error;
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
@ -11,15 +11,31 @@ pub struct FormData {
|
|||||||
email: String,
|
email: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[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(
|
pub async fn subscribe(
|
||||||
State(conn): State<PgPool>,
|
State(pool): State<PgPool>,
|
||||||
Form(form): Form<FormData>,
|
Form(form): Form<FormData>,
|
||||||
) -> impl IntoResponse {
|
) -> impl IntoResponse {
|
||||||
let request_id = Uuid::new_v4();
|
match insert_subscriber(&pool, &form).await {
|
||||||
let request_span = info_span!("Adding a new subscriber", %request_id, subscriber_email = %form.email, subscriber_name = %form.name);
|
Ok(_) => StatusCode::OK,
|
||||||
let _request_span_guard = request_span.enter();
|
Err(_) => StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
let query_span = 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(pool: &PgPool, form: &FormData) -> Result<(), sqlx::Error> {
|
||||||
|
sqlx::query!(
|
||||||
r#"
|
r#"
|
||||||
INSERT INTO subscriptions(id, email, name, subscribed_at)
|
INSERT INTO subscriptions(id, email, name, subscribed_at)
|
||||||
VALUES ($1, $2, $3, $4)
|
VALUES ($1, $2, $3, $4)
|
||||||
@ -29,14 +45,11 @@ pub async fn subscribe(
|
|||||||
form.name,
|
form.name,
|
||||||
Utc::now()
|
Utc::now()
|
||||||
)
|
)
|
||||||
.execute(&conn)
|
.execute(pool)
|
||||||
.instrument(query_span)
|
|
||||||
.await
|
.await
|
||||||
{
|
.map_err(|e| {
|
||||||
Ok(_) => StatusCode::OK,
|
error!("Failed to execute query: {:?}", e);
|
||||||
Err(e) => {
|
e
|
||||||
error!("Failed to execute query: {:?}", e);
|
})?;
|
||||||
StatusCode::INTERNAL_SERVER_ERROR
|
Ok(())
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user