-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata_documents.py
More file actions
227 lines (206 loc) · 8.57 KB
/
data_documents.py
File metadata and controls
227 lines (206 loc) · 8.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
from bson import ObjectId
from fastapi import APIRouter, Header, Body, HTTPException
import re
from models.data_documents import (
DataDocumentsRequest,
DataDocumentsResponse,
FindByIdRequest,
FindByIdResponse,
UpdateDocumentRequest,
SingleDocumentRequest,
InsertDocumentRequest,
DeleteDocumentRequest,
DocumentHistoryRequest,
DocumentHistoryResponse,
DocumentHistoryEntry,
)
from services.data_documents_service import (
find_document_by_id,
fetch_documents,
update_document,
get_single_document,
insert_document,
delete_document,
get_document_history,
)
from services.user_queries_service import get_user_id_from_token
from services.azure_auth import exchange_token_obo
from services.azure_cosmos_resources import get_connection_string
router = APIRouter()
@router.post("/documents", response_model=DataDocumentsResponse)
def get_documents(
body: DataDocumentsRequest = Body(...), authorization: str = Header(...)
):
if not authorization.startswith("Bearer "):
raise HTTPException(status_code=401, detail="Invalid token format")
user_token = authorization.replace("Bearer ", "")
access_token = exchange_token_obo(user_token)
connection_string = get_connection_string(body.account_id, access_token)
return fetch_documents(
connection_string=connection_string,
database_name=body.database_name,
collection_name=body.collection_name,
page=body.page,
limit=body.limit,
filter=body.filter.model_dump() if body.filter else None,
filters=[f.model_dump() for f in body.filters] if body.filters else None,
)
@router.put("/documents", response_model=dict)
def put_update_document(
body: UpdateDocumentRequest = Body(...), authorization: str = Header(...)
):
if not authorization.startswith("Bearer "):
raise HTTPException(status_code=401, detail="Invalid token format")
user_token = authorization.replace("Bearer ", "")
access_token = exchange_token_obo(user_token)
connection_string = get_connection_string(body.account_id, access_token)
user_id = get_user_id_from_token(authorization.replace("Bearer ", ""))
updated_doc = update_document(
connection_string=connection_string,
database_name=body.database_name,
collection_name=body.collection,
document_id=body.id,
content=body.content,
user_email=user_id,
)
if updated_doc:
# Convert ObjectId to $oid format for JSON compatibility
if "_id" in updated_doc and isinstance(updated_doc["_id"], ObjectId):
updated_doc["_id"] = {"$oid": str(updated_doc["_id"])}
return updated_doc
raise HTTPException(
status_code=404,
detail=f"Document with ID '{body.id}' not found or not updated.",
)
@router.post("/find_by_id", response_model=FindByIdResponse)
def find_by_id(body: FindByIdRequest = Body(...), authorization: str = Header(...)):
if not authorization.startswith("Bearer "):
raise HTTPException(status_code=401, detail="Invalid token format")
user_token = authorization.replace("Bearer ", "")
access_token = exchange_token_obo(user_token)
connection_string = get_connection_string(body.account_id, access_token)
doc, collection_name = find_document_by_id(
connection_string=connection_string,
database_name=body.database_name,
collection_names=", ".join(body.collection_names),
document_id=body.document_id,
key_context=body.key_context,
)
if doc:
# Convert ObjectId to $oid format for JSON compatibility
if "_id" in doc and isinstance(doc["_id"], ObjectId):
doc["_id"] = {"$oid": str(doc["_id"])}
return FindByIdResponse(document=doc, collectionName=collection_name)
raise HTTPException(
status_code=404,
detail=f"Document with ID '{body.document_id}' not found in any of the provided collections.",
)
@router.post("/document", response_model=dict)
def single_document(
body: SingleDocumentRequest = Body(...), authorization: str = Header(...)
):
if not authorization.startswith("Bearer "):
raise HTTPException(status_code=401, detail="Invalid token format")
user_token = authorization.replace("Bearer ", "")
access_token = exchange_token_obo(user_token)
connection_string = get_connection_string(body.account_id, access_token)
doc = get_single_document(
connection_string=connection_string,
database_name=body.database_name,
collection_name=body.collection_name,
document_id=body.document_id,
)
if doc:
if "_id" in doc and isinstance(doc["_id"], ObjectId):
doc["_id"] = {"$oid": str(doc["_id"])}
return doc
raise HTTPException(
status_code=404, detail=f"Document with ID '{body.document_id}' not found."
)
@router.post("/insert_document", response_model=dict)
def insert_document_route(
body: InsertDocumentRequest = Body(...), authorization: str = Header(...)
):
if not authorization.startswith("Bearer "):
raise HTTPException(status_code=401, detail="Invalid token format")
user_token = authorization.replace("Bearer ", "")
access_token = exchange_token_obo(user_token)
connection_string = get_connection_string(body.account_id, access_token)
user_id = get_user_id_from_token(authorization.replace("Bearer ", ""))
inserted_doc = insert_document(
connection_string=connection_string,
database_name=body.database_name,
collection_name=body.collection_name,
document=body.document,
user_email=user_id,
)
if inserted_doc:
if "_id" in inserted_doc and isinstance(inserted_doc["_id"], ObjectId):
inserted_doc["_id"] = {"$oid": str(inserted_doc["_id"])}
return inserted_doc
raise HTTPException(status_code=500, detail="Failed to insert document.")
# Delete document endpoint
@router.post("/delete_document", response_model=dict)
def delete_document_route(
body: DeleteDocumentRequest = Body(...), authorization: str = Header(...)
):
if not authorization.startswith("Bearer "):
raise HTTPException(status_code=401, detail="Invalid token format")
user_token = authorization.replace("Bearer ", "")
access_token = exchange_token_obo(user_token)
connection_string = get_connection_string(body.account_id, access_token)
user_id = get_user_id_from_token(authorization.replace("Bearer ", ""))
success = delete_document(
connection_string=connection_string,
database_name=body.database_name,
collection_name=body.collection_name,
document_id=body.document_id,
user_email=user_id,
)
if success:
return {"success": True}
raise HTTPException(
status_code=404,
detail=f"Document with ID '{body.document_id}' not found or could not be deleted.",
)
@router.post("/document_history", response_model=DocumentHistoryResponse)
def get_document_history_route(
body: DocumentHistoryRequest = Body(...), authorization: str = Header(...)
):
if not authorization.startswith("Bearer "):
raise HTTPException(status_code=401, detail="Invalid token format")
user_token = authorization.replace("Bearer ", "")
access_token = exchange_token_obo(user_token)
connection_string = get_connection_string(body.account_id, access_token)
# Extract account name from connection string for database_name format
match = re.search(r"//([^:@]+)", connection_string)
account_name = match.group(1) if match else "unknown"
account_database = f"{account_name}.{body.database_name}"
try:
history_entries, total_count = get_document_history(
database_name=account_database,
collection_name=body.collection_name,
document_id=body.document_id,
)
# Convert to DocumentHistoryEntry objects
entries = [
DocumentHistoryEntry(
id=entry["id"],
user_email=entry["user_email"],
operation=entry["operation"],
timestamp_utc=entry["timestamp_utc"],
diff_data=entry["diff_data"],
database_name=entry["database_name"],
collection_name=entry["collection_name"],
)
for entry in history_entries
]
return DocumentHistoryResponse(
document_id=body.document_id,
history_entries=entries,
total_entries=total_count,
)
except Exception as e:
raise HTTPException(
status_code=500, detail=f"Failed to retrieve document history: {str(e)}"
)