refactor: changes

This commit is contained in:
Sandro Eiler 2024-01-21 22:00:10 +01:00
parent 476eed4559
commit f4deaceb27
7 changed files with 137 additions and 12 deletions

View file

@ -15,13 +15,15 @@ pub struct Settings {
/// * `password`: the DB pasword
/// * `port`: the DB port
/// * `host`: the DB host address
/// * `database_name`: the DB name
/// * `name`: the DB name
pub struct DatabaseSettings {
pub username: String,
pub password: String,
pub port: u16,
pub host: String,
pub database_name: String,
pub name: String,
#[serde(default)]
pub require_ssl: bool,
}
/// Provides the application settings
@ -39,7 +41,7 @@ impl DatabaseSettings {
pub fn connection_string(&self) -> String {
format!(
"postgres://{}:{}@{}:{}/{}",
self.username, self.password, self.host, self.port, self.database_name
self.username, self.password, self.host, self.port, self.name
)
}
}

View file

@ -1,5 +1,8 @@
use std::time::Duration;
use learn_axum::configuration::get_configuration;
use learn_axum::startup;
use sqlx::postgres::PgPoolOptions;
use tokio::net::TcpListener;
#[tokio::main]
@ -7,5 +10,11 @@ async fn main() {
let configuration = get_configuration().expect("Failed to read configuration.");
let addr = format!("127.0.0.1:{}", configuration.application_port);
let listener = TcpListener::bind(addr).await.unwrap(); //.expect("Unable to bind to port");
startup::run(listener).await.unwrap();
let pool = PgPoolOptions::new()
.max_connections(5)
.acquire_timeout(Duration::from_secs(3))
.connect(&configuration.database.connection_string())
.await
.expect("can't connect to database");
startup::run(listener, pool).await.unwrap();
}

View file

@ -1,16 +1,18 @@
use axum::routing::IntoMakeService;
use axum::serve::Serve;
use axum::Router;
use sqlx::PgPool;
use tokio::net::TcpListener;
/// API routing
pub fn app() -> Router {
pub fn app(connection: PgPool) -> Router {
Router::new()
.with_state(connection)
.merge(crate::routes::routes_health_check())
.merge(crate::routes::routes_subscriptions())
}
/// Start the server
pub fn run(listener: TcpListener) -> Serve<IntoMakeService<Router>, Router> {
axum::serve(listener, app().into_make_service())
pub fn run(listener: TcpListener, connection: PgPool) -> Serve<IntoMakeService<Router>, Router> {
axum::serve(listener, app(connection).into_make_service())
}