|
| 1 | +#![deny(clippy::pedantic)] |
| 2 | +#![allow(clippy::missing_errors_doc, clippy::missing_panics_doc)] |
| 3 | + |
| 4 | +extern crate core; |
| 5 | + |
| 6 | +pub mod app_config; |
| 7 | +pub mod file_cache; |
| 8 | +pub mod filesystem; |
| 9 | +pub mod render; |
| 10 | +pub mod templates; |
| 11 | +pub mod utils; |
| 12 | +pub mod webserver; |
| 13 | + |
| 14 | +use crate::app_config::AppConfig; |
| 15 | +use crate::filesystem::FileSystem; |
| 16 | +use crate::webserver::database::{FileCache, ParsedSqlFile}; |
| 17 | +use std::env; |
| 18 | +use std::net::SocketAddr; |
| 19 | +use std::path::PathBuf; |
| 20 | +use templates::AllTemplates; |
| 21 | +use webserver::Database; |
| 22 | + |
| 23 | +pub const TEMPLATES_DIR: &str = "sqlpage/templates"; |
| 24 | +pub const MIGRATIONS_DIR: &str = "sqlpage/migrations"; |
| 25 | + |
| 26 | +pub struct AppState { |
| 27 | + pub db: Database, |
| 28 | + all_templates: AllTemplates, |
| 29 | + sql_file_cache: FileCache<ParsedSqlFile>, |
| 30 | + file_system: FileSystem, |
| 31 | +} |
| 32 | + |
| 33 | +impl AppState { |
| 34 | + pub async fn init(config: &AppConfig) -> anyhow::Result<Self> { |
| 35 | + // Connect to the database |
| 36 | + let db = Database::init(config).await?; |
| 37 | + let all_templates = AllTemplates::init()?; |
| 38 | + let web_root = get_web_root(); |
| 39 | + let mut sql_file_cache = FileCache::new(); |
| 40 | + let file_system = FileSystem::init(&web_root, &db).await; |
| 41 | + sql_file_cache.add_static( |
| 42 | + PathBuf::from("index.sql"), |
| 43 | + ParsedSqlFile::new(&db, include_str!("../index.sql")).await, |
| 44 | + ); |
| 45 | + Ok(AppState { |
| 46 | + db, |
| 47 | + all_templates, |
| 48 | + sql_file_cache, |
| 49 | + file_system, |
| 50 | + }) |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +pub fn get_web_root() -> PathBuf { |
| 55 | + env::var("WEB_ROOT").map_or_else( |
| 56 | + |_| PathBuf::from(&std::path::Component::CurDir), |
| 57 | + PathBuf::from, |
| 58 | + ) |
| 59 | +} |
| 60 | + |
| 61 | +pub struct Config { |
| 62 | + pub listen_on: SocketAddr, |
| 63 | +} |
0 commit comments