refactor
This commit is contained in:
46
backend/src/handlers/config.rs
Normal file
46
backend/src/handlers/config.rs
Normal file
@@ -0,0 +1,46 @@
|
||||
use axum::{
|
||||
extract::State,
|
||||
http::HeaderMap,
|
||||
response::IntoResponse,
|
||||
Json,
|
||||
};
|
||||
use std::{fs, sync::Arc};
|
||||
use tracing::error;
|
||||
|
||||
use crate::{
|
||||
auth::check_auth,
|
||||
error::AppError,
|
||||
models::SiteConfig,
|
||||
AppState,
|
||||
};
|
||||
|
||||
pub async fn get_config(State(state): State<Arc<AppState>>) -> impl IntoResponse {
|
||||
let config_path = state.data_dir.join("config.json");
|
||||
let config = fs::read_to_string(&config_path)
|
||||
.ok()
|
||||
.and_then(|c| serde_json::from_str::<SiteConfig>(&c).ok())
|
||||
.unwrap_or_default();
|
||||
|
||||
Json(config)
|
||||
}
|
||||
|
||||
pub async fn update_config(
|
||||
State(state): State<Arc<AppState>>,
|
||||
headers: HeaderMap,
|
||||
Json(payload): Json<SiteConfig>,
|
||||
) -> Result<Json<SiteConfig>, AppError> {
|
||||
check_auth(&headers, &state.admin_token)?;
|
||||
|
||||
let config_path = state.data_dir.join("config.json");
|
||||
let config_str = serde_json::to_string_pretty(&payload).map_err(|e| {
|
||||
error!("Serialization error: {}", e);
|
||||
AppError::Internal("Serialization error".to_string(), Some(e.to_string()))
|
||||
})?;
|
||||
|
||||
fs::write(&config_path, config_str).map_err(|e| {
|
||||
error!("Write error for config: {}", e);
|
||||
AppError::Internal("Write error".to_string(), Some(e.to_string()))
|
||||
})?;
|
||||
|
||||
Ok(Json(payload))
|
||||
}
|
||||
Reference in New Issue
Block a user