add database connection to backend
This commit is contained in:
@ -1,8 +1,12 @@
|
||||
use std::sync::mpsc;
|
||||
|
||||
use clap::Parser;
|
||||
use nuchat::AppState;
|
||||
use nuchat::Config;
|
||||
use nuchat::NuState;
|
||||
use nuchat::app;
|
||||
use sqlx::Pool;
|
||||
use sqlx::Postgres;
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::signal;
|
||||
use tracing::info;
|
||||
@ -22,6 +26,14 @@ struct Args {
|
||||
/// Admin secret to use, leave blank to disable
|
||||
#[arg(long)]
|
||||
admin_secret: Option<String>,
|
||||
|
||||
/// postgres base url, should container users and host info
|
||||
#[arg(long, default_value = "postgres://postgres:postgres@localhost:5432/")]
|
||||
postgres_url: String,
|
||||
|
||||
/// name of database to use
|
||||
#[arg(long, default_value = "nuchat_dev")]
|
||||
database: String,
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
@ -37,16 +49,24 @@ async fn main() {
|
||||
.with(tracing_subscriber::fmt::layer().with_target(false))
|
||||
.init();
|
||||
|
||||
let pool = Pool::<Postgres>::connect(&config.0.postgres_url)
|
||||
.await
|
||||
.expect("Could not connect to database");
|
||||
|
||||
let listener = TcpListener::bind(format!("{}:{}", config.0.host, config.0.port))
|
||||
.await
|
||||
.unwrap();
|
||||
tracing::debug!("listening on {}", listener.local_addr().unwrap());
|
||||
|
||||
let (app, rx) = app(&config.0);
|
||||
axum::serve(listener, app)
|
||||
let state = AppState::new(NuState::new(pool.clone(), config.0));
|
||||
let (app, rx) = app(&state);
|
||||
axum::serve(listener, app.with_state(state))
|
||||
.with_graceful_shutdown(shutdown_signal(rx))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
pool.close().await;
|
||||
|
||||
info!("Server stopped");
|
||||
}
|
||||
|
||||
@ -91,6 +111,8 @@ impl BinConfig {
|
||||
port: args.port,
|
||||
host: args.host,
|
||||
admin_secret: args.admin_secret,
|
||||
postgres_url: args.postgres_url,
|
||||
database_name: args.database,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user