diff --git a/backend/main.py b/backend/main.py index 3ccf1c4..bc04e52 100644 --- a/backend/main.py +++ b/backend/main.py @@ -36,34 +36,38 @@ async def get_posts(db: db_dependency): @app.post('/', status_code=status.HTTP_201_CREATED) async def create_thread(db: db_dependency, data: PostCreate): - # Create the post - post = Post( - author=data.author, - title=data.title, - content=data.content - ) - db.add(post) - db.commit() + try: + # Create the post + post = Post( + author=data.author, + title=data.title, + content=data.content + ) + db.add(post) + db.flush() - # Create the thread - thread = Thread( - author=post.author, - title=post.title, - content=post.content - ) - db.add(thread) - db.commit() + # Create the thread + thread = Thread( + author=post.author, + title=post.title, + content=post.content + ) + db.add(thread) + db.flush() - # Update the Post with thread_id - post.thread_id = thread.id - db.commit() + # Update the Post with thread_id + post.thread_id = thread.id + db.commit() - return { - 'id': post.id, - 'author': post.author, - 'title': post.title, - 'content': post.content - } + return { + 'id': post.id, + 'author': post.author, + 'title': post.title, + 'content': post.content + } + except Exception as e: + db.rollback() + raise HTTPException(status_code=400, detail=str(e)) @app.get('/{thread_id}', status_code=status.HTTP_200_OK) @@ -95,7 +99,7 @@ async def create_reply(db: db_dependency, data: PostCreate, thread_id: int = Pat 'content': post.content } - raise HTTPException(404, f'Could not find thread') + raise HTTPException(status_code=404, detail='Could not find thread') @app.get('/catalog', status_code=status.HTTP_200_OK)