Add AppState, DB and Snafu

This commit is contained in:
gabatxo1312 2026-01-26 01:05:10 +01:00
commit a3c0b194e1
11 changed files with 2512 additions and 143 deletions

51
src/state/config.rs Normal file
View file

@ -0,0 +1,51 @@
use snafu::prelude::*;
use tokio::fs::read_to_string;
use camino::Utf8PathBuf;
use serde::{Deserialize, Serialize};
use xdg::BaseDirectories;
#[derive(Snafu, Debug)]
pub enum ConfigError {
#[snafu(display("File doesn't exist at path : {path}"))]
FailedReadConfig {
path: Utf8PathBuf,
source: std::io::Error,
},
#[snafu(display("Failed parse config : {path}"))]
FailedParseConfig {
path: Utf8PathBuf,
source: toml::de::Error,
},
}
#[derive(Clone, Deserialize, Serialize, Debug)]
pub struct AppConfig {
#[serde(default = "AppConfig::default_sqlite_path")]
pub database_path: Utf8PathBuf,
}
impl AppConfig {
pub async fn new() -> Result<Self, ConfigError> {
// TODO: Remove this
let path = Utf8PathBuf::from("/home/torrpenn/projects/Gabatxo1312/bookforge/config.toml");
let content = read_to_string(&path).await.context(FailedReadConfigSnafu {
path: path.to_path_buf(),
})?;
toml::from_str(&content).context(FailedParseConfigSnafu {
path: path.to_path_buf(),
})
}
pub fn xdg_base_directories() -> BaseDirectories {
BaseDirectories::with_prefix("bookforge")
}
pub fn default_sqlite_path() -> Utf8PathBuf {
let config_dir = Self::xdg_base_directories().get_config_home().unwrap();
Utf8PathBuf::from_path_buf(config_dir).unwrap()
}
}

30
src/state/error.rs Normal file
View file

@ -0,0 +1,30 @@
use askama::Template;
use askama_web::WebTemplate;
use axum::response::{IntoResponse, Response};
use snafu::prelude::*;
use crate::state::config::ConfigError;
#[derive(Template, WebTemplate)]
#[template(path = "error.html")]
struct ErrorTemplate {}
#[derive(Snafu, Debug)]
#[snafu(visibility(pub))]
pub enum AppStateError {
Error,
#[snafu(display("Sqlite Error"))]
Sqlite {
source: sea_orm::error::DbErr,
},
#[snafu(display("Config Error"))]
ConfigError {
source: ConfigError,
},
}
impl IntoResponse for AppStateError {
fn into_response(self) -> Response {
ErrorTemplate {}.into_response()
}
}

27
src/state/mod.rs Normal file
View file

@ -0,0 +1,27 @@
use sea_orm::{Database, DatabaseConnection};
use snafu::prelude::*;
use crate::state::config::AppConfig;
use error::*;
pub mod config;
pub mod error;
#[derive(Clone, Debug)]
pub struct AppState {
pub config: AppConfig,
pub db: DatabaseConnection,
}
impl AppState {
pub async fn new() -> Result<Self, AppStateError> {
let config: AppConfig = AppConfig::new().await.context(ConfigSnafu)?;
let db: DatabaseConnection =
Database::connect(format!("sqlite:{}?mode=rwc", &config.database_path))
.await
.context(SqliteSnafu)?;
Ok(Self { config, db })
}
}