diff --git a/src/routes/subscriptions.rs b/src/routes/subscriptions.rs index 928bf26..97335ec 100644 --- a/src/routes/subscriptions.rs +++ b/src/routes/subscriptions.rs @@ -11,6 +11,15 @@ 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(Self { email, name }) + } +} + #[allow(clippy::async_yields_async)] #[tracing::instrument( name = "Adding a new subscriber", @@ -20,22 +29,11 @@ pub struct FormData { subscriber_name = %form.name ) )] - pub async fn subscribe(form: web::Form, pool: web::Data) -> HttpResponse { - // `web::Form` is a wrapper around `FormData` - // `form.0` gives us access to the underlying `FormData` - let name = match SubscriberName::parse(form.0.name) { - Ok(name) => name, + let new_subscriber = match form.0.try_into() { + Ok(form) => form, Err(_) => return HttpResponse::BadRequest().finish(), }; - let email = match SubscriberEmail::parse(form.0.email) { - Ok(email) => email, - Err(_) => return HttpResponse::BadRequest().finish(), - }; - let new_subscriber = NewSubscriber { - email: email, - name: name, - }; match insert_subscriber(&pool, &new_subscriber).await { Ok(_) => HttpResponse::Ok().finish(), Err(_) => HttpResponse::InternalServerError().finish(),