Skip to content

Commit

Permalink
Adding DB conncetion to subscription
Browse files Browse the repository at this point in the history
Signed-off-by: Anthony M. Bonafide <AnthonyMBonafide@gmail.com>
  • Loading branch information
AnthonyMBonafide committed Mar 27, 2024
1 parent ae2b978 commit 6b4e97a
Show file tree
Hide file tree
Showing 6 changed files with 53 additions and 6 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.

11 changes: 10 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,20 @@ actix-web = "4"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
serde = { version = "1", features = ["derive"] }
config = "0.14"
uuid = { version = "1", features = ["v4"] }
chrono = { version = "0.4.22", default-features = false, features = ["clock"] }

[dependencies.sqlx]
verion = "0.7"
default-features = false
features = ["runtime-tokio-rustls", "macros", "postgres", "uuid","chrono","migrate"]
features = [
"runtime-tokio-rustls",
"macros",
"postgres",
"uuid",
"chrono",
"migrate",
]

[dev-dependencies]
reqwest = "0.12"
8 changes: 7 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
use std::net::TcpListener;

use sqlx::{Connection, PgConnection};
use zero2prod::{configuration::get_configuration, run};

#[tokio::main]
async fn main() -> Result<(), std::io::Error> {
let config = get_configuration().expect("Failed to read configuration");
let address = format!("127.0.0.1:{}", config.application_port);
let config = get_configuration().expect("Failed to get configuration");
let connection = PgConnection::connect(&config.database.connection_string())
.await
.expect("Failed to connect to database");

let listener = TcpListener::bind(address)?;
run(listener)?.await
run(listener, connection)?.await
}
20 changes: 19 additions & 1 deletion src/routes/subscriptions.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,29 @@
use actix_web::{web, HttpResponse};
use chrono::Utc;
use sqlx::PgConnection;
use uuid::Uuid;

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

pub async fn subscribe(_form: web::Form<FormData>) -> HttpResponse {
pub async fn subscribe(
form: web::Form<FormData>,
connection: web::Data<PgConnection>,
) -> HttpResponse {
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(connection.get_ref())
.await;
HttpResponse::Ok().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::PgConnection;
use std::net::TcpListener;

pub fn run(tcp_listener: TcpListener) -> Result<Server, std::io::Error> {
let server = HttpServer::new(|| {
pub fn run(tcp_listener: TcpListener, connection: PgConnection) -> Result<Server, std::io::Error> {
let connection = web::Data::new(connection);
let server = HttpServer::new(move || {
App::new()
.route("/health_check", web::get().to(health_check))
.route("/subscribe", web::post().to(subscribe))
.app_data(connection.clone())
})
.listen(tcp_listener)?
.run();
Expand Down
8 changes: 7 additions & 1 deletion tests/health_check.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,13 @@ async fn subscribe_returns_400_for_missing_form_data() {
fn spawn_app() -> String {
let listener = TcpListener::bind("127.0.0.1:0").expect("Failed to bind port");
let port = listener.local_addr().unwrap().port();
let server = run(listener).expect("Failed to bind address");
let config = get_configuration().expect("Failed to get configuration");
let connection = PgConnection::connect(&config.database.connection_string())
.await
.expect("Failed to connect to database");

let server = run(listener, connection).expect("Failed to bind address");

let _server_run = tokio::spawn(server);
std::mem::drop(_server_run);
format!("http://127.0.0.1:{}", port)
Expand Down

0 comments on commit 6b4e97a

Please sign in to comment.