98 行
3.1 KiB
Python
98 行
3.1 KiB
Python
"""Repository for integration logs."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
from typing import Any
|
|
|
|
from database.db_helper import Database
|
|
|
|
|
|
class IntegrationRepository:
|
|
def __init__(self, database: Database):
|
|
self.database = database
|
|
|
|
@property
|
|
def placeholder(self) -> str:
|
|
return self.database._placeholder
|
|
|
|
def record(self, payload: dict[str, Any]) -> dict[str, Any]:
|
|
placeholder = self.placeholder
|
|
conn = self.database.connect()
|
|
try:
|
|
conn.execute(
|
|
f"""
|
|
INSERT INTO integration_logs (
|
|
integration_log_id,
|
|
integration_name,
|
|
action,
|
|
status,
|
|
request_json,
|
|
response_json,
|
|
error_message
|
|
) VALUES (
|
|
{placeholder}, {placeholder}, {placeholder}, {placeholder},
|
|
{placeholder}, {placeholder}, {placeholder}
|
|
)
|
|
""",
|
|
(
|
|
payload["integration_log_id"],
|
|
payload["integration_name"],
|
|
payload["action"],
|
|
payload["status"],
|
|
_json_or_none(payload.get("request")),
|
|
_json_or_none(payload.get("response")),
|
|
payload.get("error_message"),
|
|
),
|
|
)
|
|
conn.commit()
|
|
finally:
|
|
conn.close()
|
|
return payload
|
|
|
|
def list(self, integration_name: str | None = None, limit: int = 50) -> list[dict[str, Any]]:
|
|
placeholder = self.placeholder
|
|
where = ""
|
|
params: list[Any] = []
|
|
if integration_name:
|
|
where = f"WHERE integration_name = {placeholder}"
|
|
params.append(integration_name)
|
|
conn = self.database.connect()
|
|
try:
|
|
rows = conn.execute(
|
|
f"""
|
|
SELECT integration_log_id, integration_name, action, status, request_json, response_json, error_message, created_at
|
|
FROM integration_logs
|
|
{where}
|
|
ORDER BY created_at DESC
|
|
LIMIT {placeholder}
|
|
""",
|
|
tuple(params + [limit]),
|
|
).fetchall()
|
|
finally:
|
|
conn.close()
|
|
return [
|
|
{
|
|
"integration_log_id": row["integration_log_id"],
|
|
"integration_name": row["integration_name"],
|
|
"action": row["action"],
|
|
"status": row["status"],
|
|
"request": _json_loads(row["request_json"]),
|
|
"response": _json_loads(row["response_json"]),
|
|
"error_message": row["error_message"],
|
|
"created_at": str(row["created_at"]),
|
|
}
|
|
for row in rows
|
|
]
|
|
|
|
|
|
def _json_or_none(value: Any | None) -> str | None:
|
|
if value is None:
|
|
return None
|
|
return json.dumps(value, ensure_ascii=False, sort_keys=True)
|
|
|
|
|
|
def _json_loads(value: str | None) -> dict[str, Any]:
|
|
if not value:
|
|
return {}
|
|
return json.loads(value)
|