File size: 2,249 Bytes
408128e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from fastapi import APIRouter, Depends, HTTPException
from typing import Annotated
from ..middlewares.auth_middleware import get_current_user
from ..models.users import User
from ..models.words import WordSchema
from ..configs.database_config import db
from ..utils.response_fmt import jsonResponseFmt
from bson import ObjectId
import random

router = APIRouter(prefix="/word", tags=["Words"])
collection = db["word"]

user_dependency = Annotated[User, Depends(get_current_user)]


def list_word_controlller(user):
    user_id = user.get("id")
    try:
        print("user_id", user_id)
        words = WordSchema.read_all_words_by_user_id(user_id)
        return words

    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


def add_word_controller(user, word):
    user_id = user.get("id")
    try:
        existing_word = WordSchema.check_existing_word(word.word, user_id)
        if existing_word:
            return jsonResponseFmt(None, msg="Existed", code=400)
        random.shuffle(word.options)
        WordSchema(**word.dict()).create(user_id)
        return jsonResponseFmt(None, code=201)
    except Exception as e:
        return jsonResponseFmt(None, msg=str(e), code=500)


def update_word_controller(user, word_id, word_data):
    user_id = user.get("id")
    try:
        print("user", user)
        print("word_id", word_id)
        print("word_data", word_data)

        word_data.user_id = user_id
        print("word_data", word_data.dict())
        WordSchema(**word_data.dict()).update(str(word_id))
        return jsonResponseFmt(None, code=200)
    except Exception as e:
        return jsonResponseFmt(None, msg=str(e), code=500)


def delete_word_controller(user, word_id):
    user_id = user.get("id")
    try:
        existing_word = collection.find_one(
            {"_id": ObjectId(word_id), "user_id": user_id}
        )
        if not existing_word:
            return jsonResponseFmt(None, msg="Word not found", code=404)
        collection.delete_one({"_id": ObjectId(word_id)})
        return jsonResponseFmt(None, code=200)
    except Exception as e:
        return jsonResponseFmt(None, msg=str(e), code=500)