import json
import os
import azure.functions as func
from azure.cosmos import CosmosClient
app = func.FunctionApp(http_auth_level=func.AuthLevel.ANONYMOUS)
# Created once per cold start and reused across invocations (cheaper and faster).
_client = CosmosClient.from_connection_string(os.environ["COSMOS_CONNECTION_STRING"])
_container = _client.get_database_client(
os.environ.get("COSMOS_DATABASE", "employeesdb")
).get_container_client(os.environ.get("COSMOS_CONTAINER", "employeeProfile"))
def _json(body, status=200):
return func.HttpResponse(json.dumps(body), status_code=status, mimetype="application/json")
# Replaces getEmployee.py (DynamoDB scan)
@app.route(route="employees", methods=["GET"])
def get_employees(req: func.HttpRequest) -> func.HttpResponse:
items = _container.query_items(
query="SELECT c.empId, c.empFirstName, c.empLastName, c.empAge FROM c",
enable_cross_partition_query=True,
)
return _json(list(items))
# Replaces insertEmployeeData.py (DynamoDB put_item)
@app.route(route="employees", methods=["POST"])
def save_employee(req: func.HttpRequest) -> func.HttpResponse:
try:
body = req.get_json()
emp_id = str(body["empId"]).strip()
item = {
"id": emp_id, # Cosmos DB requires a field called "id"
"empId": emp_id, # partition key
"empFirstName": str(body["empFirstName"]).strip(),
"empLastName": str(body["empLastName"]).strip(),
"empAge": str(body["empAge"]).strip(),
}
except (ValueError, KeyError):
return _json({"error": "empId, empFirstName, empLastName and empAge are required"}, 400)
if not emp_id:
return _json({"error": "empId must not be empty"}, 400)
_container.upsert_item(item) # same insert-or-overwrite behaviour as put_item
return _json({"message": f"Saved {item['empFirstName']}"})