Skip to content

Commit

Permalink
code in chapter 6.14.1
Browse files Browse the repository at this point in the history
refactor using try_from()
  • Loading branch information
cnoam committed Nov 15, 2023
1 parent 83a5553 commit 3415e2e
Show file tree
Hide file tree
Showing 2 changed files with 161 additions and 25 deletions.
162 changes: 146 additions & 16 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

24 changes: 15 additions & 9 deletions src/routes/subscriptions.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use actix_web::{HttpResponse, web};
use sqlx::PgPool;
use uuid::Uuid;
use sqlx::types::chrono::Utc;
use uuid::Uuid;

use crate::domain::*;

Expand All @@ -11,6 +11,16 @@ 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 })
}
}

// you can test this with:
// curl -X POST localhost:8000/subscriptions -H "Content-Type: application/x-www-form-urlencoded" --data "name=noam&email=g@g.com"

Expand All @@ -25,16 +35,12 @@ subscriber_name = % form.name
)]
pub(crate) async fn subscribe(form: web::Form<FormData>,
pool: web::Data<PgPool>, ) -> HttpResponse {
let name = match SubscriberName::parse(form.0.name){
Ok(name) => name,
Err(_) => return HttpResponse::BadRequest().finish(),
};
let email = match SubscriberEmail::parse(form.0.email){
Ok(em) => em,
let new_subscriber = match form.0.try_into() {
Ok(form) => form,
Err(_) => return HttpResponse::BadRequest().finish(),
};
let subscriber = NewSubscriber {email, name};
match insert_subscriber(&pool, &subscriber).await {

match insert_subscriber(&pool, &new_subscriber).await {
Ok(_) => HttpResponse::Ok().finish(),
Err(_) => HttpResponse::InternalServerError().finish()
}
Expand Down

0 comments on commit 3415e2e

Please sign in to comment.