diff --git a/Cargo.lock b/Cargo.lock index 42c3606..69b7e32 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2478,6 +2478,9 @@ name = "uuid" version = "1.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "79daa5ed5740825c40b389c5e50312b9c86df53fccd33f281df655642b43869d" +dependencies = [ + "getrandom", +] [[package]] name = "vcpkg" @@ -2718,11 +2721,13 @@ name = "zero2prod" version = "0.1.0" dependencies = [ "actix-web", + "chrono", "config", "reqwest", "serde", "sqlx", "tokio", + "uuid", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index f7cded6..ddf0844 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,9 +14,11 @@ name = "zero2prod" [dependencies] actix-web = "4" +chrono = { version = "0.4.22", default-features = false, features = ["clock"] } config = "0.13" serde = { version = "1", features = ["derive"] } tokio = { version = "1", features = ["macros", "rt-multi-thread"] } +uuid = { version = "1", features = ["v4"] } [dependencies.sqlx] version = "0.7" diff --git a/src/configuration.rs b/src/configuration.rs index 11e7ee4..950d671 100644 --- a/src/configuration.rs +++ b/src/configuration.rs @@ -20,6 +20,13 @@ impl DatabaseSettings { self.username, self.password, self.host, self.port, self.database_name ) } + + pub fn connection_string_without_db(&self) -> String { + format!( + "postgres://{}:{}@{}:{}", + self.username, self.password, self.host, self.port + ) + } } pub fn get_configuration() -> Result { diff --git a/src/main.rs b/src/main.rs index 84cd09a..384f4fb 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,11 +1,15 @@ +use sqlx::PgPool; use std::net::TcpListener; use zero2prod::{configuration::get_configuration, startup::run}; #[tokio::main] async fn main() -> Result<(), std::io::Error> { let configuration = get_configuration().expect("Failed to read configuration."); + let connection_pool = PgPool::connect(&configuration.database.connection_string()) + .await + .expect("Failed to connect to Postgres."); let address = format!("127.0.0.1:{}", configuration.application_port); let listener = TcpListener::bind(address)?; - run(listener)?.await + run(listener, connection_pool)?.await } diff --git a/src/routes/subscriptions.rs b/src/routes/subscriptions.rs index 2793a6e..24710c3 100644 --- a/src/routes/subscriptions.rs +++ b/src/routes/subscriptions.rs @@ -1,4 +1,7 @@ use actix_web::{web, HttpResponse}; +use chrono::Utc; +use sqlx::PgPool; +use uuid::Uuid; #[derive(serde::Deserialize)] pub struct FormData { @@ -6,6 +9,25 @@ pub struct FormData { name: String, } -pub async fn subscribe(_form: web::Form) -> HttpResponse { - HttpResponse::Ok().finish() +pub async fn subscribe(form: web::Form, pool: web::Data) -> HttpResponse { + match 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.get_ref()) + .await + { + Ok(_) => HttpResponse::Ok().finish(), + Err(e) => { + print!("Failed to execute query: {}", e); + + HttpResponse::InternalServerError().finish() + } + } } diff --git a/src/startup.rs b/src/startup.rs index e22dee6..3f70691 100644 --- a/src/startup.rs +++ b/src/startup.rs @@ -1,12 +1,15 @@ use crate::routes::{health_check, subscribe}; use actix_web::{dev::Server, web, App, HttpServer}; +use sqlx::PgPool; use std::net::TcpListener; -pub fn run(listener: TcpListener) -> Result { - let server = HttpServer::new(|| { +pub fn run(listener: TcpListener, db_pool: PgPool) -> Result { + let db_pool = web::Data::new(db_pool); + let server = HttpServer::new(move || { App::new() .route("/health_check", web::get().to(health_check)) .route("/subscriptions", web::post().to(subscribe)) + .app_data(db_pool.clone()) }) .listen(listener)? .run(); diff --git a/tests/health_check.rs b/tests/health_check.rs index 46c52d1..2303705 100644 --- a/tests/health_check.rs +++ b/tests/health_check.rs @@ -1,16 +1,17 @@ -use sqlx::{Connection, PgConnection}; +use sqlx::{Connection, Executor, PgConnection, PgPool}; use std::net::TcpListener; -use zero2prod::configuration::get_configuration; +use uuid::Uuid; +use zero2prod::configuration::{get_configuration, DatabaseSettings}; #[tokio::test] async fn health_check_works() { // Arrange - let address = spawn_app(); + let app = spawn_app().await; let client = reqwest::Client::new(); // Act let response = client - .get(&format!("{}/health_check", &address)) + .get(&format!("{}/health_check", &app.address)) .send() .await .expect("Failed to execute request."); @@ -23,18 +24,13 @@ async fn health_check_works() { #[tokio::test] async fn subscribe_returns_a_200_for_valid_form_data() { // Arrange - let app_address = spawn_app(); - let configuration = get_configuration().expect("Failed to read configuration."); - let connection_string = configuration.database.connection_string(); - let mut connection = PgConnection::connect(&connection_string) - .await - .expect("Failed to connect to Postgres."); + let app = spawn_app().await; let client = reqwest::Client::new(); // Act - let body = "name=le%20guin&email=ursula_le_guin%40fmail.com"; + let body = "name=le%20guin&email=ursula_le_guin%40gmail.com"; let response = client - .post(&format!("{}/subscriptions", &app_address)) + .post(&format!("{}/subscriptions", &app.address)) .header("Content-Type", "application/x-www-form-urlencoded") .body(body) .send() @@ -45,7 +41,7 @@ async fn subscribe_returns_a_200_for_valid_form_data() { assert_eq!(200, response.status().as_u16()); let saved = sqlx::query!("select email, name from subscriptions") - .fetch_one(&mut connection) + .fetch_one(&app.db_pool) .await .expect("Failed to fetch saved subscription."); @@ -56,7 +52,7 @@ async fn subscribe_returns_a_200_for_valid_form_data() { #[tokio::test] async fn subscribe_returns_a_400_when_data_is_missing() { // Arrange - let app_address = spawn_app(); + let app = spawn_app().await; let client = reqwest::Client::new(); let test_cases = vec![ ("name=le%20guin", "missing the email"), @@ -67,7 +63,7 @@ async fn subscribe_returns_a_400_when_data_is_missing() { for (invalid_body, error_message) in test_cases { // Act let response = client - .post(&format!("{}/subscriptions", &app_address)) + .post(&format!("{}/subscriptions", &app.address)) .header("Content-Type", "application/x-www-form-url-encoded") .body(invalid_body) .send() @@ -84,11 +80,46 @@ async fn subscribe_returns_a_400_when_data_is_missing() { } } -fn spawn_app() -> String { +pub struct TestApp { + pub address: String, + pub db_pool: PgPool, +} + +async fn spawn_app() -> TestApp { let listener = TcpListener::bind("127.0.0.1:0").expect("Failed to bind random port."); let port = listener.local_addr().unwrap().port(); - let server = zero2prod::startup::run(listener).expect("Failed to bind address."); + let address = format!("http://127.0.0.1:{}", port); + + let mut configuration = get_configuration().expect("Failed to read configuration."); + configuration.database.database_name = Uuid::new_v4().to_string(); + let connection_pool = configure_database(&configuration.database).await; + + let server = zero2prod::startup::run(listener, connection_pool.clone()) + .expect("Failed to bind address."); let _ = tokio::spawn(server); - format!("http://127.0.0.1:{}", port) + TestApp { + address, + db_pool: connection_pool, + } +} + +pub async fn configure_database(config: &DatabaseSettings) -> PgPool { + let mut connection = PgConnection::connect(&config.connection_string_without_db()) + .await + .expect("Failed to connect to Postgres."); + connection + .execute(format!(r#"create database "{}";"#, config.database_name).as_str()) + .await + .expect("Failed to create database."); + + let connection_pool = PgPool::connect(&config.connection_string()) + .await + .expect("Failed to connect to Postgres."); + sqlx::migrate!("./migrations") + .run(&connection_pool) + .await + .expect("Failed to migrate the database."); + + connection_pool }