You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

73 rivejä
2.4 KiB

  1. import json
  2. from typing import List, Dict, Any, Optional
  3. from fastapi.encoders import jsonable_encoder
  4. from schemas.reslevis import ZoneAreaDefinitionItem
  5. from .config import ZONE_AREA_DEFINITION_JSON_PATH
  6. from .gateway import _LockedFile, _atomic_write, _norm_str
  7. class ZoneAreaDefinitionJsonRepository:
  8. def __init__(self, json_path: str = ZONE_AREA_DEFINITION_JSON_PATH):
  9. self.path = json_path
  10. def _read_all(self) -> List[Dict[str, Any]]:
  11. with _LockedFile(self.path, "r") as fp:
  12. try:
  13. fp.seek(0)
  14. data = fp.read().strip()
  15. return json.loads(data) if data else []
  16. except json.JSONDecodeError:
  17. return []
  18. def _write_all(self, rows: List[Dict[str, Any]]) -> None:
  19. payload = json.dumps(rows, ensure_ascii=False, indent=2)
  20. _atomic_write(self.path, payload)
  21. def _index_by_uuid(self, rows: List[Dict[str, Any]], item_uuid: str) -> Optional[int]:
  22. target = _norm_str(item_uuid)
  23. for idx, row in enumerate(rows):
  24. if _norm_str(row.get("UUID")) == target:
  25. return idx
  26. return None
  27. def list(self, item_uuid: Optional[str] = None) -> List[Dict[str, Any]]:
  28. rows = self._read_all()
  29. if item_uuid:
  30. idx = self._index_by_uuid(rows, item_uuid)
  31. return [rows[idx]] if idx is not None else []
  32. return rows
  33. def add(self, item: ZoneAreaDefinitionItem) -> None:
  34. rows = self._read_all()
  35. obj = jsonable_encoder(item)
  36. obj_uuid = _norm_str(obj.get("UUID"))
  37. if self._index_by_uuid(rows, obj_uuid) is not None:
  38. raise ValueError(f"ZoneAreaDefinition con UUID '{obj_uuid}' già presente")
  39. rows.append(obj)
  40. self._write_all(rows)
  41. def update(self, item: ZoneAreaDefinitionItem) -> None:
  42. rows = self._read_all()
  43. obj = jsonable_encoder(item)
  44. obj_uuid = _norm_str(obj.get("UUID"))
  45. idx = self._index_by_uuid(rows, obj_uuid)
  46. if idx is None:
  47. raise ValueError(f"ZoneAreaDefinition con UUID '{obj_uuid}' non trovato")
  48. rows[idx] = obj
  49. self._write_all(rows)
  50. def remove(self, item_uuid: str) -> None:
  51. rows = self._read_all()
  52. idx = self._index_by_uuid(rows, item_uuid)
  53. if idx is None:
  54. raise ValueError(f"ZoneAreaDefinition con UUID '{item_uuid}' non trovato")
  55. del rows[idx]
  56. self._write_all(rows)