use std::sync::OnceLock;
use std::sync::Arc;
#[cfg(feature = "db")]
use alun_db::Db;
#[cfg(feature = "cache")]
use alun_cache::SharedCache;
use alun_config::ConfigManager;
#[cfg(feature = "template")]
use alun_template::TemplateEngine;
#[cfg(feature = "db")]
static DB: OnceLock<Db> = OnceLock::new();
#[cfg(feature = "cache")]
static CACHE: OnceLock<SharedCache> = OnceLock::new();
static CONFIG: OnceLock<Arc<ConfigManager>> = OnceLock::new();
#[cfg(feature = "template")]
static TEMPLATE: OnceLock<TemplateEngine> = OnceLock::new();
static UPLOAD_PATH: OnceLock<String> = OnceLock::new();
static DOWNLOAD_PATH: OnceLock<String> = OnceLock::new();
#[cfg(feature = "db")]
pub fn set_db(db: Db) -> Result<(), &'static str> {
DB.set(db).map_err(|_| "数据库资源已初始化")
}
#[cfg(feature = "cache")]
pub fn set_cache(cache: SharedCache) -> Result<(), &'static str> {
CACHE.set(cache).map_err(|_| "缓存资源已初始化")
}
pub fn set_config(config: Arc<ConfigManager>) -> Result<(), &'static str> {
CONFIG.set(config).map_err(|_| "配置资源已初始化")
}
#[cfg(feature = "template")]
pub fn set_template(template: TemplateEngine) -> Result<(), &'static str> {
TEMPLATE.set(template).map_err(|_| "模板引擎已初始化")
}
#[cfg(feature = "db")]
pub fn db() -> &'static Db {
DB.get().expect("数据库未初始化,请先调用 set_db()")
}
#[cfg(feature = "db")]
pub fn try_db() -> Option<&'static Db> {
DB.get()
}
#[cfg(feature = "cache")]
pub fn cache() -> &'static SharedCache {
CACHE.get().expect("缓存未初始化,请先调用 set_cache()")
}
#[cfg(feature = "cache")]
pub fn try_cache() -> Option<&'static SharedCache> {
CACHE.get()
}
pub fn config() -> &'static Arc<ConfigManager> {
CONFIG.get().expect("配置未初始化,请先调用 set_config()")
}
pub fn try_config() -> Option<&'static Arc<ConfigManager>> {
CONFIG.get()
}
pub fn cfg() -> &'static alun_config::AppConfig {
config().get()
}
#[cfg(feature = "template")]
pub fn render_template<T: serde::Serialize>(
name: &str,
context: &T,
) -> alun_core::Result<String> {
TEMPLATE.get()
.ok_or_else(|| alun_core::Error::Template("模板引擎未初始化".into()))
.and_then(|t| t.render(name, context))
}
#[cfg(feature = "template")]
pub fn try_template() -> Option<&'static TemplateEngine> {
TEMPLATE.get()
}
pub fn set_upload_path(path: String) -> Result<(), &'static str> {
UPLOAD_PATH.set(path).map_err(|_| "上传路径已初始化")
}
pub fn upload_path() -> &'static str {
UPLOAD_PATH.get().map(|s| s.as_str()).unwrap_or("uploads")
}
pub fn try_upload_path() -> Option<&'static str> {
UPLOAD_PATH.get().map(|s| s.as_str())
}
pub fn set_download_path(path: String) -> Result<(), &'static str> {
DOWNLOAD_PATH.set(path).map_err(|_| "下载路径已初始化")
}
pub fn download_path() -> &'static str {
DOWNLOAD_PATH.get().map(|s| s.as_str()).unwrap_or("downloads")
}
pub fn try_download_path() -> Option<&'static str> {
DOWNLOAD_PATH.get().map(|s| s.as_str())
}