diff --git a/src/domain.rs b/src/domain.rs index df654a7..c42f4cb 100644 --- a/src/domain.rs +++ b/src/domain.rs @@ -1,5 +1,10 @@ use unicode_segmentation::UnicodeSegmentation; +pub struct NewSubscriber { + pub email: String, + pub name: SubscriberName, +} + pub struct SubscriberName(String); impl SubscriberName { @@ -37,3 +42,9 @@ impl SubscriberName { } } } + +impl AsRef for SubscriberName { + fn as_ref(&self) -> &str { + &self.0 + } +} diff --git a/src/routes/subscriptions.rs b/src/routes/subscriptions.rs index fd801af..2d3ea6e 100644 --- a/src/routes/subscriptions.rs +++ b/src/routes/subscriptions.rs @@ -1,3 +1,4 @@ +use crate::domain::{NewSubscriber, SubscriberName}; use actix_web::{web, HttpResponse}; use chrono::Utc; use sqlx::PgPool; @@ -21,7 +22,11 @@ pub async fn subscribe( form: web::Form, pool: web::Data, ) -> Result { - insert_subscriber(&pool, &form) + let new_subscriber = NewSubscriber { + email: form.0.email, + name: SubscriberName::parse(form.0.name), + }; + insert_subscriber(&pool, &new_subscriber) .await .map_err(|_| HttpResponse::InternalServerError().finish())?; Ok(HttpResponse::Ok().finish()) @@ -29,17 +34,20 @@ pub async fn subscribe( #[tracing::instrument( name = "Saving new subscriber details in the database", - skip(form, pool) + skip(new_subscriber, pool) )] -pub async fn insert_subscriber(pool: &PgPool, form: &FormData) -> Result<(), sqlx::Error> { +pub async fn insert_subscriber( + pool: &PgPool, + new_subscriber: &NewSubscriber, +) -> Result<(), sqlx::Error> { sqlx::query!( r#" INSERT INTO subscriptions (id, email, name, subscribed_at) VALUES ($1, $2, $3, $4) "#, Uuid::new_v4(), - form.email, - form.name, + new_subscriber.email, + new_subscriber.name.as_ref(), Utc::now() ) .execute(pool)