Use AsRef

This commit is contained in:
Luca Palmieri 2020-12-09 22:55:00 +00:00
parent 0eaf310f29
commit 1c27412280
2 changed files with 24 additions and 5 deletions

View file

@ -1,5 +1,10 @@
use unicode_segmentation::UnicodeSegmentation;
pub struct NewSubscriber {
pub email: String,
pub name: SubscriberName,
}
pub struct SubscriberName(String);
impl SubscriberName {
@ -37,3 +42,9 @@ impl SubscriberName {
}
}
}
impl AsRef<str> for SubscriberName {
fn as_ref(&self) -> &str {
&self.0
}
}

View file

@ -1,3 +1,4 @@
use crate::domain::{NewSubscriber, SubscriberName};
use actix_web::{web, HttpResponse};
use chrono::Utc;
use sqlx::PgPool;
@ -21,7 +22,11 @@ pub async fn subscribe(
form: web::Form<FormData>,
pool: web::Data<PgPool>,
) -> Result<HttpResponse, HttpResponse> {
insert_subscriber(&pool, &form)
let new_subscriber = NewSubscriber {
email: form.0.email,
name: SubscriberName::parse(form.0.name),
};
insert_subscriber(&pool, &new_subscriber)
.await
.map_err(|_| HttpResponse::InternalServerError().finish())?;
Ok(HttpResponse::Ok().finish())
@ -29,17 +34,20 @@ pub async fn subscribe(
#[tracing::instrument(
name = "Saving new subscriber details in the database",
skip(form, pool)
skip(new_subscriber, pool)
)]
pub async fn insert_subscriber(pool: &PgPool, form: &FormData) -> Result<(), sqlx::Error> {
pub async fn insert_subscriber(
pool: &PgPool,
new_subscriber: &NewSubscriber,
) -> Result<(), sqlx::Error> {
sqlx::query!(
r#"
INSERT INTO subscriptions (id, email, name, subscribed_at)
VALUES ($1, $2, $3, $4)
"#,
Uuid::new_v4(),
form.email,
form.name,
new_subscriber.email,
new_subscriber.name.as_ref(),
Utc::now()
)
.execute(pool)