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,34 +36,38 @@ 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):
# Create the post try:
post = Post( # Create the post
author=data.author, post = Post(
title=data.title, author=data.author,
content=data.content title=data.title,
) content=data.content
db.add(post) )
db.commit() db.add(post)
db.flush()
# Create the thread # Create the thread
thread = Thread( thread = Thread(
author=post.author, author=post.author,
title=post.title, title=post.title,
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
db.commit() db.commit()
return { return {
'id': post.id, 'id': post.id,
'author': post.author, 'author': post.author,
'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)