import os import uuid import json from datetime import datetime from typing import Dict, Any, List, Optional from faker import Faker from sqlalchemy.orm import Session from database import SessionLocal, MockApiSchema, init_db fake = Faker() class MockApiEngine: """ Engine to dynamically handle CRUD requests and persist fake data to a SQL database. """ def __init__(self): # Ensure tables exist init_db() def _get_api(self, db: Session, api_id: str) -> Optional[MockApiSchema]: return db.query(MockApiSchema).filter(MockApiSchema.id == api_id).first() def delete_api_data(self, api_id: str): """Clears all data associated with an api_id.""" with SessionLocal() as db: api = self._get_api(db, api_id) if api: db.delete(api) db.commit() def generate_fake_data(self, fields: Dict[str, str], count: int = 5) -> List[Dict[str, Any]]: """Generates realistic fake data based on the provided field types and names.""" data = [] for i in range(count): item = {} for field, f_type in fields.items(): if field == "id": item[field] = i + 1 if f_type == "number" else str(uuid.uuid4()) continue f_type_lower = str(f_type).lower() field_lower = str(field).lower() if f_type_lower == "number": if any(word in field_lower for word in ["price", "cost", "amount"]): item[field] = fake.random_int(min=500, max=50000) / 100.0 else: item[field] = fake.random_int(min=1, max=1000) elif f_type_lower == "boolean": item[field] = fake.boolean() elif f_type_lower == "string": if "email" in field_lower: item[field] = fake.email() elif any(word in field_lower for word in ["user", "name"]): item[field] = fake.name() elif "phone" in field_lower: item[field] = fake.phone_number() elif "address" in field_lower: item[field] = fake.address() elif any(word in field_lower for word in ["date", "time"]): item[field] = fake.iso8601() elif any(word in field_lower for word in ["url", "image", "avatar"]): item[field] = f"https://picsum.photos/seed/{uuid.uuid4().hex[:8]}/400/300" elif any(word in field_lower for word in ["price", "cost", "amount"]): item[field] = f"${fake.random_int(min=500, max=50000) / 100.0}" elif any(word in field_lower for word in ["description", "bio"]): item[field] = fake.sentence() elif any(word in field_lower for word in ["category", "tag"]): item[field] = fake.word().capitalize() else: item[field] = fake.word() else: item[field] = fake.word() data.append(item) return data def load_from_schema(self, api_id: str, schema_dict: Dict[str, Any], user_id: str, expires_at: datetime) -> List[str]: """Parses a schema and initializes data in the database.""" entities = schema_dict.get("entities", []) routes = [] mock_data = {} for entity in entities: name = entity.get("name") fields = entity.get("fields", {}) if name and fields: mock_data[name] = self.generate_fake_data(fields) base_path = f"/mock/{api_id}/{name}" routes.extend([ f"GET {base_path}", f"GET {base_path}/{{id}}", f"POST {base_path}", f"PUT {base_path}/{{id}}", f"DELETE {base_path}/{{id}}" ]) with SessionLocal() as db: new_api = MockApiSchema( id=api_id, name=schema_dict.get("name", "Generated API"), user_id=user_id, expires_at=expires_at, mock_data=mock_data ) db.merge(new_api) db.commit() return routes async def handle_request(self, api_id: str, path: str, method: str, body: Any = None) -> Any: """Processes an incoming request against the persisted data.""" with SessionLocal() as db: api = self._get_api(db, api_id) if not api: return None parts = path.strip("/").split("/") entity_name = parts[0] if not entity_name: entities = list(api.mock_data.keys()) return { "mock_id": api_id, "message": "Specify an entity to access data.", "available_entities": entities, "example_url": f"/mock/{api_id}/{entities[0]}" if entities else None } item_id = parts[1] if len(parts) > 1 else None records = api.mock_data.get(entity_name) if records is None: return None if method == "GET": if item_id: for item in records: if str(item.get("id")) == str(item_id): return item return {"error": "Item not found"} return records if method == "POST": item = body or {} if "id" not in item: item["id"] = str(uuid.uuid4()) updated_records = list(records) updated_records.append(item) new_data = dict(api.mock_data) new_data[entity_name] = updated_records api.mock_data = new_data db.add(api) db.commit() return item if method == "PUT" and item_id: updated_records = list(records) found = False for i, item in enumerate(updated_records): if str(item.get("id")) == str(item_id): updated = body or {} updated["id"] = item["id"] updated_records[i] = updated found = True break if found: new_data = dict(api.mock_data) new_data[entity_name] = updated_records api.mock_data = new_data db.add(api) db.commit() return updated return {"error": "Item not found"} if method == "DELETE" and item_id: updated_records = list(records) deleted_data = None for i, item in enumerate(updated_records): if str(item.get("id")) == str(item_id): deleted_data = updated_records.pop(i) break if deleted_data: new_data = dict(api.mock_data) new_data[entity_name] = updated_records api.mock_data = new_data db.add(api) db.commit() return {"status": "deleted", "data": deleted_data} return {"error": "Item not found"} return {"error": "Method not allowed"}