Skip to content

Commit

Permalink
postgres db connection
Browse files Browse the repository at this point in the history
  • Loading branch information
dibakarsutradhar committed Apr 14, 2024
1 parent 656b261 commit 201c412
Show file tree
Hide file tree
Showing 5 changed files with 61 additions and 4 deletions.
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,7 @@ Cargo.toml.orig

# Ignore OS-specific files
.DS_Store
Thumbs.db
Thumbs.db

.env
configuration.yaml
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ actix-web = "4"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
reqwest = "0.11"
serde = {version = "1", features = ["derive"]}
config = "0.11"

[dependencies.sqlx]
version = "0.5.7"
Expand Down
34 changes: 34 additions & 0 deletions src/configuration.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#[derive(serde::Deserialize)]
pub struct Settings {
pub database: DatabaseSettings,
pub application_port: u16
}

#[derive(serde::Deserialize)]
pub struct DatabaseSettings {
pub username: String,
pub password: String,
pub port: u16,
pub host: String,
pub database_name: String
}

pub fn get_configuration() -> Result<Settings, config::ConfigError> {
// Initialise our configuration reader
let mut settings = config::Config::default();

// Add configuration values from a file name `configuration`
settings.merge(config::File::with_name("configuration"))?;

// Try to convert the configuration values it read into out Settings type
settings.try_into()
}

impl DatabaseSettings {
pub fn connection_string(&self) -> String {
format!(
"postgres://{}:{}@{}:{}/{}",
self.username, self.password, self.host, self.port, self.database_name
)
}
}
7 changes: 5 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
use std::net::TcpListener;
use newsletter::startup::run;
use newsletter::configuration::get_configuration;

#[tokio::main]
async fn main() -> std::io::Result<()> {
let listener = TcpListener::bind("127.0.0.1:0")
.expect("Failed to bind random port");
// Panic if we can't read configuration
let configuration = get_configuration().expect("Failed to read configuration.");
let address = format!("127.0.0.1:{}", configuration.application_port);
let listener = TcpListener::bind(address)?;
run(listener)?.await
}
18 changes: 17 additions & 1 deletion tests/health_check.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use std::net::TcpListener;
use newsletter::startup::run;
use sqlx::{PgConnection, Connection};
use newsletter::configuration::get_configuration;

fn spawn_app() -> String {
let listener = TcpListener::bind("127.0.0.1:0")
Expand Down Expand Up @@ -33,18 +35,32 @@ async fn health_check_works() {
#[tokio::test]
async fn subscribe_returns_200_for_valid_form_data() {
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 client = reqwest::Client::new();

let body = "name=dibakar%20dhar&email=where_is_dibakar%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()
.await
.expect("Failed to execute request");

assert_eq!(200, response.status().as_u16());

let saved = sqlx::query!("SELECT email, name FROM subscriptions",)
.fetch_one(&mut connection)
.await
.expect("Failed to fetch saved subscription");

assert_eq!(saved.email, "where_is_dibakar@gmail.com");
assert_eq!(saved.name, "dibakar dhar");

}

#[tokio::test]
Expand Down

0 comments on commit 201c412

Please sign in to comment.