generated from alecodes/base-template
feat: add sqlx basic config
This commit is contained in:
parent
e0e8700baa
commit
48afdaccea
6 changed files with 1598 additions and 17 deletions
30
src/main.rs
30
src/main.rs
|
|
@ -1,8 +1,11 @@
|
|||
#![allow(unused)]
|
||||
#![allow(dead_code)]
|
||||
|
||||
use compendium::{router, AppState, Error, Link, Result};
|
||||
use compendium::{router, AppState, Error, Link, Result, Tx};
|
||||
use minijinja::{Environment, Value};
|
||||
use sqlx::postgres::PgPoolOptions;
|
||||
use sqlx::PgPool;
|
||||
use std::env;
|
||||
use std::sync::Arc;
|
||||
use tower_http::trace::TraceLayer;
|
||||
use tracing::info;
|
||||
|
|
@ -37,6 +40,23 @@ fn load_templates() -> Result<Environment<'static>> {
|
|||
Ok(tmpl_env)
|
||||
}
|
||||
|
||||
async fn init_db() -> Result<PgPool> {
|
||||
let db_string = format!(
|
||||
"postgres://{}:{}@{}/{}",
|
||||
env::var("CPD_DB_USER")?,
|
||||
env::var("CPD_DB_PASSWORD")?,
|
||||
env::var("CPD_DB_HOST")?,
|
||||
env::var("CPD_DB_NAME")?
|
||||
);
|
||||
|
||||
info!("Connecting to database {}", db_string);
|
||||
|
||||
Ok(PgPoolOptions::new()
|
||||
.max_connections(5)
|
||||
.connect(&db_string)
|
||||
.await?)
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
// Logs
|
||||
|
|
@ -51,9 +71,15 @@ async fn main() -> Result<()> {
|
|||
|
||||
let mut tmpl_env = load_templates()?;
|
||||
|
||||
let pool = init_db().await?;
|
||||
|
||||
let (tx_state, tx_layer) = Tx::setup(pool);
|
||||
|
||||
let app = router::new()
|
||||
.layer(TraceLayer::new_for_http().on_request(()))
|
||||
.with_state(AppState::new(tmpl_env));
|
||||
.with_state(AppState::new(tmpl_env))
|
||||
.layer(tx_layer)
|
||||
.with_state(tx_state);
|
||||
|
||||
// Add hot reload only on dev mode
|
||||
#[cfg(debug_assertions)]
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue