File size: 8,085 Bytes
7efb19e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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"}