mirror of
https://github.com/LukeMathWalker/zero-to-production.git
synced 2024-12-18 14:06:37 +00:00
Use AsRef
This commit is contained in:
parent
0eaf310f29
commit
1c27412280
2 changed files with 24 additions and 5 deletions
|
@ -1,5 +1,10 @@
|
||||||
use unicode_segmentation::UnicodeSegmentation;
|
use unicode_segmentation::UnicodeSegmentation;
|
||||||
|
|
||||||
|
pub struct NewSubscriber {
|
||||||
|
pub email: String,
|
||||||
|
pub name: SubscriberName,
|
||||||
|
}
|
||||||
|
|
||||||
pub struct SubscriberName(String);
|
pub struct SubscriberName(String);
|
||||||
|
|
||||||
impl SubscriberName {
|
impl SubscriberName {
|
||||||
|
@ -37,3 +42,9 @@ impl SubscriberName {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl AsRef<str> for SubscriberName {
|
||||||
|
fn as_ref(&self) -> &str {
|
||||||
|
&self.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
use crate::domain::{NewSubscriber, SubscriberName};
|
||||||
use actix_web::{web, HttpResponse};
|
use actix_web::{web, HttpResponse};
|
||||||
use chrono::Utc;
|
use chrono::Utc;
|
||||||
use sqlx::PgPool;
|
use sqlx::PgPool;
|
||||||
|
@ -21,7 +22,11 @@ pub async fn subscribe(
|
||||||
form: web::Form<FormData>,
|
form: web::Form<FormData>,
|
||||||
pool: web::Data<PgPool>,
|
pool: web::Data<PgPool>,
|
||||||
) -> Result<HttpResponse, HttpResponse> {
|
) -> 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
|
.await
|
||||||
.map_err(|_| HttpResponse::InternalServerError().finish())?;
|
.map_err(|_| HttpResponse::InternalServerError().finish())?;
|
||||||
Ok(HttpResponse::Ok().finish())
|
Ok(HttpResponse::Ok().finish())
|
||||||
|
@ -29,17 +34,20 @@ pub async fn subscribe(
|
||||||
|
|
||||||
#[tracing::instrument(
|
#[tracing::instrument(
|
||||||
name = "Saving new subscriber details in the database",
|
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!(
|
sqlx::query!(
|
||||||
r#"
|
r#"
|
||||||
INSERT INTO subscriptions (id, email, name, subscribed_at)
|
INSERT INTO subscriptions (id, email, name, subscribed_at)
|
||||||
VALUES ($1, $2, $3, $4)
|
VALUES ($1, $2, $3, $4)
|
||||||
"#,
|
"#,
|
||||||
Uuid::new_v4(),
|
Uuid::new_v4(),
|
||||||
form.email,
|
new_subscriber.email,
|
||||||
form.name,
|
new_subscriber.name.as_ref(),
|
||||||
Utc::now()
|
Utc::now()
|
||||||
)
|
)
|
||||||
.execute(pool)
|
.execute(pool)
|
||||||
|
|
Loading…
Reference in a new issue