79 lines
2.8 KiB
Python
79 lines
2.8 KiB
Python
from __future__ import annotations
|
|
|
|
import json
|
|
from pathlib import Path
|
|
|
|
from fastapi import APIRouter, Body, HTTPException
|
|
|
|
from backend.app.core.config import BackendConfig, CONFIG_PATH, load_config
|
|
|
|
router = APIRouter(prefix="/config", tags=["config"])
|
|
|
|
# Chemin vers la config frontend
|
|
FRONTEND_CONFIG_PATH = Path(__file__).resolve().parent.parent.parent.parent / "frontend" / "config_frontend.json"
|
|
|
|
|
|
@router.get("/backend", response_model=BackendConfig)
|
|
def read_backend_config() -> BackendConfig:
|
|
# expose la configuration backend en lecture seule
|
|
return load_config()
|
|
|
|
|
|
@router.put("/backend", response_model=BackendConfig)
|
|
def update_backend_config(payload: dict = Body(...)) -> BackendConfig:
|
|
current = load_config()
|
|
try:
|
|
# validation via Pydantic avant écriture
|
|
updated = current.model_copy(update=payload)
|
|
CONFIG_PATH.write_text(updated.model_dump_json(indent=2), encoding="utf-8")
|
|
load_config.cache_clear()
|
|
return load_config()
|
|
except Exception as exc: # pragma: no cover
|
|
raise HTTPException(status_code=400, detail=str(exc))
|
|
|
|
|
|
@router.get("/frontend")
|
|
def read_frontend_config() -> dict:
|
|
"""Retourne la configuration frontend."""
|
|
if not FRONTEND_CONFIG_PATH.exists():
|
|
raise HTTPException(status_code=404, detail="Config frontend introuvable")
|
|
return json.loads(FRONTEND_CONFIG_PATH.read_text(encoding="utf-8"))
|
|
|
|
|
|
@router.put("/frontend")
|
|
def update_frontend_config(payload: dict = Body(...)) -> dict:
|
|
"""Met à jour la configuration frontend."""
|
|
try:
|
|
# Charger la config actuelle
|
|
current = {}
|
|
if FRONTEND_CONFIG_PATH.exists():
|
|
current = json.loads(FRONTEND_CONFIG_PATH.read_text(encoding="utf-8"))
|
|
|
|
# Fusion profonde des configs
|
|
def deep_merge(base: dict, update: dict) -> dict:
|
|
result = base.copy()
|
|
for key, value in update.items():
|
|
if key in result and isinstance(result[key], dict) and isinstance(value, dict):
|
|
result[key] = deep_merge(result[key], value)
|
|
else:
|
|
result[key] = value
|
|
return result
|
|
|
|
updated = deep_merge(current, payload)
|
|
FRONTEND_CONFIG_PATH.write_text(
|
|
json.dumps(updated, indent=2, ensure_ascii=False),
|
|
encoding="utf-8"
|
|
)
|
|
|
|
# Mettre à jour aussi dans public/ pour le frontend dev
|
|
public_config = FRONTEND_CONFIG_PATH.parent / "public" / "config_frontend.json"
|
|
if public_config.parent.exists():
|
|
public_config.write_text(
|
|
json.dumps(updated, indent=2, ensure_ascii=False),
|
|
encoding="utf-8"
|
|
)
|
|
|
|
return updated
|
|
except Exception as exc:
|
|
raise HTTPException(status_code=400, detail=str(exc))
|