forked from mongodb-partners/MongoDB_DataAPI_Azure
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunction_app.py
More file actions
162 lines (135 loc) · 6.31 KB
/
function_app.py
File metadata and controls
162 lines (135 loc) · 6.31 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
import azure.functions as func
import logging
import json
import traceback
import os
from pymongo import MongoClient
from bson import ObjectId
from datetime import datetime
# Read flag from environment variables
ENABLE_OBJECTID_CONVERSION = os.getenv("ENABLE_OBJECTID_CONVERSION", "true").lower() == "true"
app = func.FunctionApp(http_auth_level=func.AuthLevel.FUNCTION)
def convert_objectid(document):
"""Recursively convert ObjectIds to strings."""
if isinstance(document, list):
return [convert_objectid(d) for d in document]
elif isinstance(document, dict):
return {
k: str(v) if ENABLE_OBJECTID_CONVERSION and isinstance(v, ObjectId)
else convert_objectid(v)
for k, v in document.items()
}
else:
return document
def connect_to_mongodb():
conn_str = os.environ.get("MONGODBATLAS_CLUSTER_CONNECTIONSTRING")
if not conn_str:
raise Exception("MongoDB connection string not found in environment variables.")
try:
client = MongoClient(conn_str)
return client
except Exception as e:
logging.error(f"Error connecting to MongoDB: {e}")
raise
def success_response(body):
return func.HttpResponse(
json.dumps(body, cls=DateTimeEncoder),
status_code=200,
mimetype="application/json"
)
def error_response(err):
error_message = str(err)
return func.HttpResponse(
error_message,
status_code=400,
mimetype="application/json"
)
# Used to convert datetime object(s) to string
class DateTimeEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, datetime):
return o.isoformat()
return super().default(o)
@app.route(route="mdb_dataapi/action/{operation}",methods=['POST'])
def mongodb_dataapi_replace(req: func.HttpRequest) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
client = None
try:
payload = req.get_json()
client = connect_to_mongodb()
op = req.route_params.get('operation')
# logging.info(op)
db,coll = payload.get('database'),payload.get('collection')
# logging.info(db)
# logging.info(coll)
if op == "findOne":
filter_op = payload['filter'] if 'filter' in payload else {}
projection = payload['projection'] if 'projection' in payload else {}
result = {"document": client[db][coll].find_one(filter_op, projection)}
# print("*************")
# print(result)
# print("*************")
if result['document'] is not None:
if '_id' in result['document'] and isinstance(result['document']['_id'], ObjectId):
result['document']['_id'] = str(result['document']['_id'])
elif op == "find":
agg_query = []
if 'filter' in payload and payload['filter'] != {}:
agg_query.append({"$match": payload['filter']})
if "sort" in payload and payload['sort'] != {}:
agg_query.append({"$sort": payload['sort']})
if "skip" in payload:
agg_query.append({"$skip": payload['skip']})
if 'limit' in payload:
agg_query.append({"$limit": payload['limit']})
if "projection" in payload and payload['projection'] != {}:
agg_query.append({"$project": payload['projection']})
result = {"documents": list(client[db][coll].aggregate(agg_query))}
for obj in result['documents']:
if '_id' in obj and isinstance(obj['_id'], ObjectId):
obj['_id'] = str(obj['_id'])
elif op == "insertOne":
if "document" not in payload or payload['document'] == {}:
return error_response("Send a document to insert")
insert_op = client[db][coll].insert_one(payload['document'])
result = {"insertedId": str(insert_op.inserted_id)}
elif op == "insertMany":
if "documents" not in payload or payload['documents'] == {}:
return error_response("Send a document to insert")
insert_op = client[db][coll].insert_many(payload['documents'])
result = {"insertedIds": [str(_id) for _id in insert_op.inserted_ids]}
elif op in ["updateOne", "updateMany"]:
payload['upsert'] = payload['upsert'] if 'upsert' in payload else False
if "_id" in payload['filter']:
payload['filter']['_id'] = ObjectId(payload['filter']['_id'])
if op == "/updateOne":
update_op = client[db][coll].update_one(payload['filter'], payload['update'], upsert=payload['upsert'])
else:
update_op = client[db][coll].update_many(payload['filter'], payload['update'], upsert=payload['upsert'])
result = {"matchedCount": update_op.matched_count, "modifiedCount": update_op.modified_count}
elif op in ["deleteOne", "deleteMany"]:
payload['filter'] = payload['filter'] if 'filter' in payload else {}
if "_id" in payload['filter']:
payload['filter']['_id'] = ObjectId(payload['filter']['_id'])
if op == "/deleteOne":
result = {"deletedCount": client[db][coll].delete_one(payload['filter']).deleted_count}
else:
result = {"deletedCount": client[db][coll].delete_many(payload['filter']).deleted_count}
elif op == "aggregate":
if "pipeline" not in payload or payload['pipeline'] == []:
return error_response("Send a pipeline")
docs = list(client[db][coll].aggregate(payload['pipeline']))
for obj in docs:
if '_id' in obj and isinstance(obj['_id'], ObjectId):
obj['_id'] = str(obj['_id'])
result = {"documents": docs}
else:
return error_response("Not a valid operation")
result = convert_objectid(result)
return success_response(result)
except Exception as e:
print(traceback.format_exc())
return error_response(e)
finally:
if client:
client.close()