Skip to content

Commit

Permalink
finish chapter 6, implements validator with form email and name
Browse files Browse the repository at this point in the history
  • Loading branch information
josemoura212 committed Jun 12, 2024
1 parent 5868566 commit ccc3ab7
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 16 deletions.
5 changes: 2 additions & 3 deletions spec.yaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
name: zero2prod
region: fra
region: sfo
services:
- name: zero2prod
dockerfile_path: Dockerfile
Expand Down Expand Up @@ -34,10 +34,9 @@ services:
- key: APP_DATABASE__DATABASE_NAME
scope: RUN_TIME
value: ${newsletter.DATABASE}

databases:
- engine: PG
name: newsletter
num_nodes: 1
size: db-s-dev-database
version: "12"
version: "14"
4 changes: 2 additions & 2 deletions src/domain/new_subscriber.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use super::SubscriberName;
use super::{SubscriberEmail, SubscriberName};

pub struct NewSubscriber {
pub email: String,
pub email: SubscriberEmail,
pub name: SubscriberName,
}
24 changes: 13 additions & 11 deletions src/routes/subscriptions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,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(NewSubscriber { email, name })
}
}

#[tracing::instrument(
name = "Adding a new subscriber",
skip(form, pool),
Expand All @@ -19,19 +29,11 @@ pub struct FormData {
)]

pub async fn subscribe(form: web::Form<FormData>, pool: web::Data<PgPool>) -> HttpResponse {
let name = match SubscriberName::parse(form.0.name.clone()) {
Ok(name) => name,
let new_subscriber = match form.0.try_into() {
Ok(form) => form,
Err(_) => return HttpResponse::BadRequest().finish(),
};

let _ = match SubscriberEmail::parse(form.0.email.clone()) {
Ok(email) => email,
Err(_) => return HttpResponse::BadRequest().finish(),
};
let new_subscriber = NewSubscriber {
email: form.0.email,
name,
};
match insert_subscriber(&pool, &new_subscriber).await {
Ok(_) => HttpResponse::Ok().finish(),
Err(_) => HttpResponse::InternalServerError().finish(),
Expand All @@ -52,7 +54,7 @@ pub async fn insert_subscriber(
VALUES ($1,$2,$3)
"#,
Uuid::new_v4(),
new_subscriber.email,
new_subscriber.email.as_ref(),
new_subscriber.name.as_ref(),
)
.execute(pool)
Expand Down

0 comments on commit ccc3ab7

Please sign in to comment.