Big changes, up to 3.8.5.5
This commit is contained in:
parent
bd9f5a7819
commit
679e257f7b
1
.env
Normal file
1
.env
Normal file
@ -0,0 +1 @@
|
|||||||
|
DATABASE_URL="postgres://postgres:password@localhost:5432/newsletter"
|
2
.gitignore
vendored
2
.gitignore
vendored
@ -1,6 +1,6 @@
|
|||||||
/target
|
/target
|
||||||
.vscode
|
.vscode
|
||||||
.env
|
#.env
|
||||||
.gitlab-ci-local
|
.gitlab-ci-local
|
||||||
|
|
||||||
# Added by cargo
|
# Added by cargo
|
||||||
|
795
Cargo.lock
generated
795
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
14
Cargo.toml
14
Cargo.toml
@ -13,6 +13,20 @@ name = "mail_app"
|
|||||||
[dependencies]
|
[dependencies]
|
||||||
actix-web = "4"
|
actix-web = "4"
|
||||||
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
|
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
|
||||||
|
serde = { version = "1", features = ["derive"] }
|
||||||
|
config = "0.13"
|
||||||
|
|
||||||
|
[dependencies.sqlx]
|
||||||
|
version = "0.6"
|
||||||
|
default-features = false
|
||||||
|
features = [
|
||||||
|
"runtime-tokio-rustls",
|
||||||
|
"macros",
|
||||||
|
"postgres",
|
||||||
|
"uuid",
|
||||||
|
"chrono",
|
||||||
|
"migrate"
|
||||||
|
]
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
reqwest = "0.11"
|
reqwest = "0.11"
|
7
configuration.yaml
Normal file
7
configuration.yaml
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
application_port: 8000
|
||||||
|
database:
|
||||||
|
host: "127.0.0.1"
|
||||||
|
port: 5432
|
||||||
|
username: "postgres"
|
||||||
|
password: "password"
|
||||||
|
database_name: "newsletter"
|
9
migrations/20230831130447_create_subscription_table.sql
Normal file
9
migrations/20230831130447_create_subscription_table.sql
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
-- migrations/{timestamp}_create_subscriptions_table.sql
|
||||||
|
-- Create Subscriptions Table
|
||||||
|
CREATE TABLE subscriptions(
|
||||||
|
id uuid NOT NULL,
|
||||||
|
PRIMARY KEY (id),
|
||||||
|
email TEXT NOT NULL UNIQUE,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
subscribed_at timestamptz NOT NULL
|
||||||
|
);
|
51
scripts/init_db.sh
Executable file
51
scripts/init_db.sh
Executable file
@ -0,0 +1,51 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -x
|
||||||
|
set -eo pipefail
|
||||||
|
|
||||||
|
if ! [ -x "$(command -v psql)" ]; then
|
||||||
|
echo >&2 "Error: psql is not installed."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if ! [ -x "$(command -v sqlx)" ]; then
|
||||||
|
echo >&2 "Error: sqlx is not installed."
|
||||||
|
echo >&2 "Use:"
|
||||||
|
echo >&2 " cargo install --version="~0.6" sqlx-cli"
|
||||||
|
echo >&2 " --no-default-features --feature rustls,postgres"
|
||||||
|
echo >&2 "to install."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
DB_USER="${POSTGRES_USER:=postgres}"
|
||||||
|
DB_PASSWORD="${POSTGRES_PASSWORD:=password}"
|
||||||
|
DB_NAME="${POSTGRES_DB:=newsletter}"
|
||||||
|
DB_PORT="${POSTGRES_PORT:=5432}"
|
||||||
|
DB_HOST="${POSTGRES_HOST:=localhost}"
|
||||||
|
|
||||||
|
if [[ -z "${SKIP_DOCKER}" ]]
|
||||||
|
then
|
||||||
|
docker run \
|
||||||
|
-e POSTGRES_USER=${DB_USER} \
|
||||||
|
-e POSTGRES_PASSWORD=${DB_PASSWORD} \
|
||||||
|
-e POSTGRES_DB=${DB_NAME} \
|
||||||
|
-p "${DB_PORT}":5432 \
|
||||||
|
--name "mailAppDB" \
|
||||||
|
-d postgres:alpine \
|
||||||
|
postgres -N 1000
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Ping until ready to accept commands
|
||||||
|
export PGPASSWORD="${DB_PASSWORD}"
|
||||||
|
until psql -h "${DB_HOST}" -U "${DB_USER}" -p "${DB_PORT}" -d "postgres" -c '\q'; do
|
||||||
|
>&2 echo "Postgres is still unavailable - sleeping"
|
||||||
|
sleep 1
|
||||||
|
done
|
||||||
|
|
||||||
|
>&2 echo "Postgres is running on port ${DB_PORT}, and ready to accept commands!"
|
||||||
|
|
||||||
|
DATABASE_URL=postgres://${DB_USER}:${DB_PASSWORD}@${DB_HOST}:${DB_PORT}/${DB_NAME}
|
||||||
|
export DATABASE_URL
|
||||||
|
sqlx database create
|
||||||
|
sqlx migrate run
|
||||||
|
|
||||||
|
>&2 echo "Postgres has been migrated, ready for queries!"
|
34
src/configuration.rs
Normal file
34
src/configuration.rs
Normal file
@ -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 config reader
|
||||||
|
let settings = config::Config::builder()
|
||||||
|
.add_source(
|
||||||
|
config::File::new("configuration.yaml", config::FileFormat::Yaml)
|
||||||
|
)
|
||||||
|
.build()?;
|
||||||
|
settings.try_deserialize::<Settings>()
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DatabaseSettings {
|
||||||
|
pub fn connection_string(&self) -> String {
|
||||||
|
format!(
|
||||||
|
"postgres://{}:{}@{}:{}/{}",
|
||||||
|
self.username, self.password, self.host, self.port, self.database_name
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
20
src/lib.rs
20
src/lib.rs
@ -1,17 +1,3 @@
|
|||||||
use actix_web::{web, App, HttpResponse, HttpServer};
|
pub mod configuration;
|
||||||
use actix_web::dev::Server;
|
pub mod routes;
|
||||||
use std::net::TcpListener;
|
pub mod startup;
|
||||||
|
|
||||||
async fn health_check() -> HttpResponse {
|
|
||||||
HttpResponse::Ok().finish()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn run(listener: TcpListener) -> Result<Server, std::io::Error> {
|
|
||||||
let server = HttpServer::new(|| {
|
|
||||||
App::new()
|
|
||||||
.route("/health_check", web::get().to(health_check))
|
|
||||||
})
|
|
||||||
.listen(listener)?
|
|
||||||
.run();
|
|
||||||
Ok(server)
|
|
||||||
}
|
|
@ -1,10 +1,11 @@
|
|||||||
use mail_app::run;
|
|
||||||
|
|
||||||
use std::net::TcpListener;
|
use std::net::TcpListener;
|
||||||
|
use mail_app::startup::run;
|
||||||
|
use mail_app::configuration::get_configuration;
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
async fn main() -> Result<(), std::io::Error> {
|
async fn main() -> Result<(), std::io::Error> {
|
||||||
let listener = TcpListener::bind("127.0.0.1:8000")
|
let configuration = get_configuration().expect("Failed to read config");
|
||||||
.expect("Failed to bind to port 8000");
|
let address = format!("127.0.0.1:{}", configuration.application_port);
|
||||||
|
let listener = TcpListener::bind(address)?;
|
||||||
run(listener)?.await
|
run(listener)?.await
|
||||||
}
|
}
|
||||||
|
5
src/routes/health_check.rs
Normal file
5
src/routes/health_check.rs
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
use actix_web::HttpResponse;
|
||||||
|
|
||||||
|
pub async fn health_check() -> HttpResponse {
|
||||||
|
HttpResponse::Ok().finish()
|
||||||
|
}
|
5
src/routes/mod.rs
Normal file
5
src/routes/mod.rs
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
mod health_check;
|
||||||
|
mod subscriptions;
|
||||||
|
|
||||||
|
pub use health_check::*;
|
||||||
|
pub use subscriptions::*;
|
11
src/routes/subscriptions.rs
Normal file
11
src/routes/subscriptions.rs
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
use actix_web::{web, HttpResponse};
|
||||||
|
|
||||||
|
#[derive(serde::Deserialize)]
|
||||||
|
pub struct FormData {
|
||||||
|
email: String,
|
||||||
|
name: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn subscribe(_form: web::Form<FormData>) -> HttpResponse {
|
||||||
|
HttpResponse::Ok().finish()
|
||||||
|
}
|
15
src/startup.rs
Normal file
15
src/startup.rs
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
use actix_web::{web, App, HttpServer};
|
||||||
|
use actix_web::dev::Server;
|
||||||
|
use std::net::TcpListener;
|
||||||
|
use crate::routes::{health_check, subscribe};
|
||||||
|
|
||||||
|
pub fn run(listener: TcpListener) -> Result<Server, std::io::Error> {
|
||||||
|
let server = HttpServer::new(|| {
|
||||||
|
App::new()
|
||||||
|
.route("/health_check", web::get().to(health_check))
|
||||||
|
.route("/subscriptions", web::post().to(subscribe))
|
||||||
|
})
|
||||||
|
.listen(listener)?
|
||||||
|
.run();
|
||||||
|
Ok(server)
|
||||||
|
}
|
@ -1,4 +1,17 @@
|
|||||||
use std::net::TcpListener;
|
use std::net::TcpListener;
|
||||||
|
use sqlx::{PgConnection, Connection};
|
||||||
|
use mail_app::startup::run;
|
||||||
|
use mail_app::configuration::get_configuration;
|
||||||
|
|
||||||
|
fn spawn_app() -> String {
|
||||||
|
let listener = TcpListener::bind("127.0.0.1:0").expect("Failed to bind to random port.");
|
||||||
|
let port = listener.local_addr().unwrap().port();
|
||||||
|
let server = run(listener).expect("Failed to bind address");
|
||||||
|
// Launch in background
|
||||||
|
let _spawn = tokio::spawn(server);
|
||||||
|
|
||||||
|
format!("http://127.0.0.1:{}", port)
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn health_check_works() {
|
async fn health_check_works() {
|
||||||
@ -18,13 +31,66 @@ async fn health_check_works() {
|
|||||||
assert_eq!(Some(0), response.content_length());
|
assert_eq!(Some(0), response.content_length());
|
||||||
}
|
}
|
||||||
|
|
||||||
fn spawn_app() -> String {
|
#[tokio::test]
|
||||||
let listener = TcpListener::bind("127.0.0.1:0")
|
async fn subscribe_returns_a_200_for_valid_form_data() {
|
||||||
.expect("Failed to bind to random port.");
|
// Arrange
|
||||||
let port = listener.local_addr().unwrap().port();
|
let app_address = spawn_app();
|
||||||
let server = mail_app::run(listener).expect("Failed to bind address");
|
let configuration = get_configuration().expect("Failed to get config");
|
||||||
// Launch in background
|
let connection_string = configuration.database.connection_string();
|
||||||
let _spawn = tokio::spawn(server);
|
let mut connection = PgConnection::connect(&connection_string)
|
||||||
|
.await
|
||||||
|
.expect("Failed to connect to Postgres Database.");
|
||||||
|
let client = reqwest::Client::new();
|
||||||
|
|
||||||
format!("http://127.0.0.1:{}", port)
|
// Act
|
||||||
|
let body = "name=le%20guin&email=ursula_le_guin%40gmail.com";
|
||||||
|
let response = client
|
||||||
|
.post(&format!("{}/subscriptions", &app_address))
|
||||||
|
.header("Content-Type", "application/x-www-form-urlencoded")
|
||||||
|
.body(body)
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.expect("Failed to execute request.");
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
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, "ursula_le_guin@gmail.com");
|
||||||
|
assert_eq!(saved.name, "le guin");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn subscribe_returns_a_400_when_data_is_missing() {
|
||||||
|
// Arrange
|
||||||
|
let app_address = spawn_app();
|
||||||
|
let client = reqwest::Client::new();
|
||||||
|
let test_cases = vec![
|
||||||
|
("name=le%20guin", "missing email"),
|
||||||
|
("email=ursula_le_guin%40gmail.com", "missing name"),
|
||||||
|
("", "missing both name and email"),
|
||||||
|
];
|
||||||
|
|
||||||
|
for (invalid_body, error_message) in test_cases {
|
||||||
|
// Act
|
||||||
|
let response = client
|
||||||
|
.post(&format!("{}/subscriptions", &app_address))
|
||||||
|
.header("Content-Type", "application/x-www-form-urlencoded")
|
||||||
|
.body(invalid_body)
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.expect("Failed to execute request.");
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
assert_eq!(
|
||||||
|
400,
|
||||||
|
response.status().as_u16(),
|
||||||
|
"The API id not fail wth 400 Bad Request when the payload was {}.",
|
||||||
|
error_message
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user