Skip to content

Commit

Permalink
feat: store subscriber
Browse files Browse the repository at this point in the history
  • Loading branch information
migueloller committed Oct 12, 2023
1 parent 675f4f3 commit 6b2de61
Show file tree
Hide file tree
Showing 7 changed files with 97 additions and 23 deletions.
5 changes: 5 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
7 changes: 7 additions & 0 deletions src/configuration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Settings, config::ConfigError> {
Expand Down
6 changes: 5 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
@@ -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
}
26 changes: 24 additions & 2 deletions src/routes/subscriptions.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,33 @@
use actix_web::{web, HttpResponse};
use chrono::Utc;
use sqlx::PgPool;
use uuid::Uuid;

#[derive(serde::Deserialize)]
pub struct FormData {
email: String,
name: String,
}

pub async fn subscribe(_form: web::Form<FormData>) -> HttpResponse {
HttpResponse::Ok().finish()
pub async fn subscribe(form: web::Form<FormData>, pool: web::Data<PgPool>) -> 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()
}
}
}
7 changes: 5 additions & 2 deletions src/startup.rs
Original file line number Diff line number Diff line change
@@ -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<Server, std::io::Error> {
let server = HttpServer::new(|| {
pub fn run(listener: TcpListener, db_pool: PgPool) -> Result<Server, std::io::Error> {
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();
Expand Down
67 changes: 49 additions & 18 deletions tests/health_check.rs
Original file line number Diff line number Diff line change
@@ -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.");
Expand All @@ -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()
Expand All @@ -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.");

Expand All @@ -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"),
Expand All @@ -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()
Expand All @@ -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
}

0 comments on commit 6b2de61

Please sign in to comment.