File size: 1,860 Bytes
78a40dc
0f24635
 
 
aeeb750
0f24635
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe417f6
764f303
0f24635
3e73980
0f24635
fe417f6
 
e435e58
 
237ed98
e435e58
 
 
fe417f6
0f24635
 
 
78a40dc
 
 
 
0f24635
 
237ed98
 
 
d6461d3
764f303
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
from fastapi import APIRouter, Depends, HTTPException, status
from motor.motor_asyncio import AsyncIOMotorDatabase
from src.core.database import mongo_db
from src.models.mongo.cv_model import CVModel
from pydantic import BaseModel, Field
from typing import Optional, Dict, Any
from bson import ObjectId

router = APIRouter()

class CVCreate(BaseModel):
    user_id: str
    parsed_data: Dict[str, Any]
    raw_text: Optional[str] = None
    upload_date: str

class CVResponse(BaseModel):
    id: str = Field(alias="_id")
    user_id: str
    parsed_data: Dict[str, Any]
    raw_text: Optional[str] = None
    upload_date: str

    class Config:
        populate_by_name = True
        json_encoders = {ObjectId: str}
        from_attributes = True

@router.post("/cvs", response_model=CVResponse)
async def create_cv(cv: CVCreate, db: AsyncIOMotorDatabase = Depends(lambda: mongo_db)):
    cv_entry = cv.model_dump(by_alias=True, exclude_unset=True)
    cv_id = await CVModel.create(db, CVModel.collection_name, cv_entry)

    cv_entry['id'] = str(cv_id) 
    
    if '_id' in cv_entry:
        cv_entry.pop('_id') 
        
    return CVResponse(**cv_entry)

@router.get("/cvs/{cv_id}", response_model=CVResponse)
async def get_cv_by_id(cv_id: str, db: AsyncIOMotorDatabase = Depends(lambda: mongo_db)):
    if not ObjectId.is_valid(cv_id):
        raise HTTPException(status_code=400, detail="ID de CV invalide")
    
    cv = await CVModel.get(db, CVModel.collection_name, {"_id": ObjectId(cv_id)})
    if cv is None:
        raise HTTPException(status_code=404, detail="CV not found")
    
    # MODIFICATION : Convertit explicitement l'ObjectId en str avant de retourner l'objet.
    # On supprime la clé '_id' d'origine pour ne pas avoir de conflits avec la clé 'id' lors de la validation.
    cv['id'] = str(cv.pop('_id'))
    return CVResponse(**cv)