Files
mnote/rust/crates/mnote-web/src/app.rs
T

76 lines
2.7 KiB
Rust
Raw Normal View History

use crate::middleware::request_context::inject_request_context;
use crate::routes::build_router;
use axum::Router;
use std::env;
use std::sync::Arc;
use tower_http::trace::TraceLayer;
#[derive(Debug, Clone)]
pub struct AppConfig {
pub service_name: String,
pub service_version: String,
pub bind_addr: String,
pub hermes_base_path: String,
pub compat_next_base_path: String,
pub convex_url: Option<String>,
pub convex_admin_key: Option<String>,
pub allow_dev_fixtures: bool,
pub dev_user_id: String,
pub dev_user_name: String,
pub dev_user_email: String,
}
impl AppConfig {
pub fn from_env() -> Self {
Self {
service_name: env::var("MNOTE_WEB_SERVICE_NAME").unwrap_or_else(|_| "mnote-web".into()),
service_version: env::var("MNOTE_WEB_SERVICE_VERSION")
.unwrap_or_else(|_| env!("CARGO_PKG_VERSION").into()),
bind_addr: env::var("MNOTE_WEB_BIND").unwrap_or_else(|_| "127.0.0.1:3104".into()),
hermes_base_path: env::var("MNOTE_WEB_HERMES_BASE_PATH")
.unwrap_or_else(|_| "/api/hermes".into()),
compat_next_base_path: env::var("MNOTE_WEB_COMPAT_NEXT_BASE_PATH")
.unwrap_or_else(|_| "/api/compat/next".into()),
convex_url: env::var("CONVEX_SELF_HOSTED_URL")
.ok()
.or_else(|| env::var("NEXT_PUBLIC_CONVEX_URL").ok())
.map(|value| value.trim().trim_end_matches('/').to_string())
.filter(|value| !value.is_empty()),
convex_admin_key: env::var("CONVEX_SELF_HOSTED_ADMIN_KEY")
.ok()
.map(|value| value.trim().to_string())
.filter(|value| !value.is_empty()),
allow_dev_fixtures: env::var("MNOTE_WEB_ALLOW_DEV_FIXTURES")
.ok()
.map(|value| matches!(value.trim(), "1" | "true" | "TRUE" | "yes" | "YES"))
.unwrap_or(false),
dev_user_id: env::var("DEV_USER_ID").unwrap_or_else(|_| "dev-user".into()),
dev_user_name: env::var("DEV_USER_NAME").unwrap_or_else(|_| "开发用户".into()),
dev_user_email: env::var("DEV_USER_EMAIL").unwrap_or_else(|_| "dev@mnote.local".into()),
}
}
}
#[derive(Debug, Clone)]
pub struct AppState {
config: Arc<AppConfig>,
}
impl AppState {
pub fn new(config: AppConfig) -> Self {
Self {
config: Arc::new(config),
}
}
pub fn config(&self) -> &AppConfig {
self.config.as_ref()
}
}
pub fn build_app(state: AppState) -> Router {
build_router(state)
.layer(TraceLayer::new_for_http())
.layer(axum::middleware::from_fn(inject_request_context))
}