wag-managment-api-service-v.../Services/Postgres/Models/response.py

50 lines
1.3 KiB
Python

from typing import Any, Dict, List, Optional, TypeVar, Generic
T = TypeVar('T')
class PostgresResponse(Generic[T]):
"""Base class for Postgres response handling."""
def __init__(
self,
status: bool,
message: str,
data: Optional[T] = None,
error: Optional[str] = None,
):
self.status = status
self.message = message
self.data = data
self.error = error
if isinstance(data, dict):
self.data_type = "dict"
elif isinstance(data, list):
self.data_type = "list"
else:
self.data_type = None
def as_dict(self) -> Dict[str, Any]:
"""Convert response to dictionary format."""
return {
"status": self.status,
"message": self.message,
"data": self.data,
"dataType": self.data_type,
"error": self.error,
}
@property
def all(self) -> Optional[List[T]]:
"""Get all data items if data is a list."""
if isinstance(self.data, list):
return self.data
return None
@property
def first(self) -> Optional[T]:
"""Get first data item if data is a list."""
if isinstance(self.data, list) and self.data:
return self.data[0]
return None