refactor: better indication of data conversion
This commit is contained in:
parent
bfc09ae0f0
commit
20acf5bde0
1 changed files with 14 additions and 11 deletions
|
|
@ -19,6 +19,16 @@ struct FormData {
|
|||
name: String,
|
||||
}
|
||||
|
||||
impl TryFrom<FormData> for NewSubscriber {
|
||||
type Error = String;
|
||||
|
||||
fn try_from(value: FormData) -> Result<Self, Self::Error> {
|
||||
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<PgPool>, Form(form): Form<FormData>) -> 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue