11from datetime import datetime , timezone
22
3+ from bson import ObjectId
4+ from bson .errors import InvalidId
35from fastapi import APIRouter , HTTPException , Request , status
46from pymongo .errors import DuplicateKeyError
57
1012
1113@router .get ("/all" , response_model = list [SchemaDefinition ])
1214async def get_all_schemas (request : Request ):
13- schemas_collection = request .app .state .schemas_collection
14- docs = schemas_collection .find ({})
15- return [SchemaDefinition (** doc ) async for doc in docs ]
15+ collection = request .app .state .schemas_collection
16+ docs = collection .find ({})
17+ all_docs = []
18+ async for doc in docs :
19+ doc ["_id" ] = str (doc ["_id" ])
20+ all_docs .append (SchemaDefinition (** doc ))
21+ return all_docs
1622
1723
1824@router .post (
@@ -28,43 +34,63 @@ async def add_schema(request: Request, schema: SchemaDefinition):
2834 detail = "`content` must not be null." ,
2935 )
3036
31- schemas_collection = request .app .state .schemas_collection
37+ collection = request .app .state .schemas_collection
3238
3339 # Build doc to insert, excluding None fields
3440 doc = schema .model_dump (exclude_none = True )
3541 doc ["created_at" ] = datetime .now (timezone .utc )
3642
3743 try :
38- await schemas_collection .insert_one (doc )
44+ result = await collection .insert_one (doc )
3945 except DuplicateKeyError :
4046 # you created a unique index on title
4147 raise HTTPException (
4248 status_code = status .HTTP_409_CONFLICT ,
4349 detail = "A schema with this title already exists." ,
4450 )
45-
51+ doc [ "_id" ] = str ( result . inserted_id )
4652 return SchemaDefinition (** doc )
4753
4854
49- # @router.post("/add", response_model=SchemaDefinition)
50- # async def add_schema(schema: SchemaDefinition) -> dict[str, Any]:
51- # """
52- # Add a new schema. If `id` is missing/empty, generate one; always refresh `updated_at`.
53- # """
54- # doc = schema.dict()
55+ @router .delete ("/delete/{title}" , status_code = status .HTTP_200_OK )
56+ async def delete_schema_by_title (
57+ request : Request ,
58+ title : str | None = None ,
59+ ):
60+ """
61+ Delete a schema by _id OR by title.
62+ Provide exactly one of: id or title.
63+ """
64+ if not title :
65+ raise HTTPException (
66+ status_code = status .HTTP_400_BAD_REQUEST ,
67+ detail = "Provide exactly one of: id or title" ,
68+ )
69+
70+ collection = request .app .state .schemas_collection
71+ result = await collection .delete_one ({"title" : title })
72+ if result .deleted_count == 0 :
73+ raise HTTPException (404 , f"Schema with title `{ title } ` not found" )
5574
56- # # Guarantee a usable id
57- # if not isinstance(doc.get("id"), str) or not doc["id"].strip():
58- # doc["id"] = str(uuid4())
75+ return {"message" : "Schema deleted" }
5976
60- # # Server-side timestamp
61- # doc["updated_at"] = datetime.utcnow()
6277
63- # # Insert as-is (no ObjectId conversions)
64- # schemas_collection.insert_one(doc)
78+ @router .delete ("/delete/id/{id}" , status_code = status .HTTP_200_OK )
79+ async def delete_schema_by_id (
80+ request : Request ,
81+ id : str | None = None ,
82+ ):
83+ collection = request .app .state .schemas_collection
84+ try :
85+ oid = ObjectId (id )
86+ except InvalidId :
87+ raise HTTPException (400 , "Invalid Mongo ObjectId" )
88+
89+ result = await collection .delete_one ({"_id" : oid })
90+ if result .deleted_count == 0 :
91+ raise HTTPException (404 , f"Schema with id `{ id } ` not found" )
6592
66- # # Return exactly what we stored
67- # return jsonable_encoder(doc)
93+ return {"message" : "Schema deleted" }
6894
6995
7096# @router.put("/update/{id}", response_model=dict[str, str])
0 commit comments