consolidate database transactions when creating new thread

This commit is contained in:
agatha 2024-04-05 19:41:57 -04:00
parent b3feb1b7a0
commit e4f0105a6e

View File

@ -36,6 +36,7 @@ async def get_posts(db: db_dependency):
@app.post('/', status_code=status.HTTP_201_CREATED) @app.post('/', status_code=status.HTTP_201_CREATED)
async def create_thread(db: db_dependency, data: PostCreate): async def create_thread(db: db_dependency, data: PostCreate):
try:
# Create the post # Create the post
post = Post( post = Post(
author=data.author, author=data.author,
@ -43,7 +44,7 @@ async def create_thread(db: db_dependency, data: PostCreate):
content=data.content content=data.content
) )
db.add(post) db.add(post)
db.commit() db.flush()
# Create the thread # Create the thread
thread = Thread( thread = Thread(
@ -52,7 +53,7 @@ async def create_thread(db: db_dependency, data: PostCreate):
content=post.content content=post.content
) )
db.add(thread) db.add(thread)
db.commit() db.flush()
# Update the Post with thread_id # Update the Post with thread_id
post.thread_id = thread.id post.thread_id = thread.id
@ -64,6 +65,9 @@ async def create_thread(db: db_dependency, data: PostCreate):
'title': post.title, 'title': post.title,
'content': post.content '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) @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 '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) @app.get('/catalog', status_code=status.HTTP_200_OK)