zero-to-production/chapter05/src/routes/subscriptions.rs
Luca Palmieri 0a4addc6bb
Chapter 5 (#13)
* Add chapter 5

* Basic deployment stuff

* Fix Dockerfile.

* Add an explicit connection timeout.

* Align port with configuration.

* Use debug for faster feedback loops.

* Add address configuration.

* Provision database.

* Use structured options.

* Add configuration

* Fix typo.

* Customise deserialization logic.

* Change to Require.

* Fix spec.

* Add a few more things to the dockerignore file.

* Update to match chapter.

* Add base configuration.

* Amend configuratiohn.

Co-authored-by: LukeMathWalker <rust@lpalmieri.com>
2020-11-01 21:25:11 +00:00

53 lines
1.2 KiB
Rust

use actix_web::{web, HttpResponse};
use chrono::Utc;
use sqlx::PgPool;
use uuid::Uuid;
#[derive(serde::Deserialize)]
pub struct FormData {
email: String,
name: String,
}
#[tracing::instrument(
name = "Adding a new subscriber",
skip(form, pool),
fields(
email = %form.email,
name = %form.name
)
)]
pub async fn subscribe(
form: web::Form<FormData>,
pool: web::Data<PgPool>,
) -> Result<HttpResponse, HttpResponse> {
insert_subscriber(&pool, &form)
.await
.map_err(|_| HttpResponse::InternalServerError().finish())?;
Ok(HttpResponse::Ok().finish())
}
#[tracing::instrument(
name = "Saving new subscriber details in the database",
skip(form, pool)
)]
pub async fn insert_subscriber(pool: &PgPool, form: &FormData) -> 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,
Utc::now()
)
.execute(pool)
.await
.map_err(|e| {
tracing::error!("Failed to execute query: {:?}", e);
e
})?;
Ok(())
}