Skip to content

Commit

Permalink
Chapter 6 done
Browse files Browse the repository at this point in the history
  • Loading branch information
armallen committed Sep 19, 2024
1 parent 0e6900b commit c9e0650
Showing 1 changed file with 11 additions and 13 deletions.
24 changes: 11 additions & 13 deletions src/routes/subscriptions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,15 @@ pub 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 })
}
}

#[allow(clippy::async_yields_async)]
#[tracing::instrument(
name = "Adding a new subscriber",
Expand All @@ -20,22 +29,11 @@ pub struct FormData {
subscriber_name = %form.name
)
)]

pub async fn subscribe(form: web::Form<FormData>, pool: web::Data<PgPool>) -> 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(),
Expand Down

0 comments on commit c9e0650

Please sign in to comment.