From 20acf5bde0f5d076f95210fc6df8013d1493df76 Mon Sep 17 00:00:00 2001 From: Sandro Eiler Date: Mon, 12 Feb 2024 11:12:25 +0100 Subject: [PATCH] refactor: better indication of data conversion --- src/routes/subscriptions.rs | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/src/routes/subscriptions.rs b/src/routes/subscriptions.rs index b1ea5e4..a135509 100644 --- a/src/routes/subscriptions.rs +++ b/src/routes/subscriptions.rs @@ -19,6 +19,16 @@ 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 }) + } +} + #[tracing::instrument( name = "Adding a new subscriber", skip(form, pool), @@ -29,25 +39,18 @@ struct FormData { ) )] pub async fn subscribe(State(pool): State, Form(form): Form) -> Response { - let name = match SubscriberName::parse(form.name) { - Ok(name) => name, + let new_subscriber = match form.try_into() { + Ok(form) => form, Err(_) => { - return (StatusCode::BAD_REQUEST, "Invalid name").into_response(); + return (StatusCode::BAD_REQUEST, "Invalid subscription.").into_response(); } }; - let email = match SubscriberEmail::parse(form.email) { - Ok(email) => email, - Err(_) => { - return (StatusCode::BAD_REQUEST, "Invalid email address").into_response(); - } - }; - let new_subscriber = NewSubscriber { email, name }; match insert_subscriber(&pool, &new_subscriber).await { Ok(_) => { return (StatusCode::OK,).into_response(); } Err(_) => { - return (StatusCode::INTERNAL_SERVER_ERROR, "Something went wrong").into_response(); + return (StatusCode::INTERNAL_SERVER_ERROR, "Something went wrong.").into_response(); } } }