diff --git a/spec.yaml b/spec.yaml index 0f1dfc1..0a2e3d6 100644 --- a/spec.yaml +++ b/spec.yaml @@ -1,5 +1,5 @@ name: zero2prod -region: fra +region: sfo services: - name: zero2prod dockerfile_path: Dockerfile @@ -34,10 +34,9 @@ services: - key: APP_DATABASE__DATABASE_NAME scope: RUN_TIME value: ${newsletter.DATABASE} - databases: - engine: PG name: newsletter num_nodes: 1 size: db-s-dev-database - version: "12" + version: "14" diff --git a/src/domain/new_subscriber.rs b/src/domain/new_subscriber.rs index 0f2f8bd..873e65a 100644 --- a/src/domain/new_subscriber.rs +++ b/src/domain/new_subscriber.rs @@ -1,6 +1,6 @@ -use super::SubscriberName; +use super::{SubscriberEmail, SubscriberName}; pub struct NewSubscriber { - pub email: String, + pub email: SubscriberEmail, pub name: SubscriberName, } diff --git a/src/routes/subscriptions.rs b/src/routes/subscriptions.rs index 2ce8af1..83ed187 100644 --- a/src/routes/subscriptions.rs +++ b/src/routes/subscriptions.rs @@ -9,6 +9,16 @@ pub struct FormData { name: String, } +impl TryFrom for NewSubscriber { + type Error = String; + + fn try_from(value: FormData) -> Result { + let name = SubscriberName::parse(value.name)?; + let email = SubscriberEmail::parse(value.email)?; + Ok(NewSubscriber { email, name }) + } +} + #[tracing::instrument( name = "Adding a new subscriber", skip(form, pool), @@ -19,19 +29,11 @@ pub struct FormData { )] pub async fn subscribe(form: web::Form, pool: web::Data) -> HttpResponse { - let name = match SubscriberName::parse(form.0.name.clone()) { - Ok(name) => name, + let new_subscriber = match form.0.try_into() { + Ok(form) => form, Err(_) => return HttpResponse::BadRequest().finish(), }; - let _ = match SubscriberEmail::parse(form.0.email.clone()) { - Ok(email) => email, - Err(_) => return HttpResponse::BadRequest().finish(), - }; - let new_subscriber = NewSubscriber { - email: form.0.email, - name, - }; match insert_subscriber(&pool, &new_subscriber).await { Ok(_) => HttpResponse::Ok().finish(), Err(_) => HttpResponse::InternalServerError().finish(), @@ -52,7 +54,7 @@ pub async fn insert_subscriber( VALUES ($1,$2,$3) "#, Uuid::new_v4(), - new_subscriber.email, + new_subscriber.email.as_ref(), new_subscriber.name.as_ref(), ) .execute(pool)