Refactor CreatePost and EditPost logic to handle cover images with transactions; improve error handling and logging
All checks were successful
CI - Build and Push / Build and Push Docker Image (push) Successful in 56s

This commit is contained in:
2025-10-25 21:54:52 +08:00
parent 0e4a7e29a3
commit efc20ac1ab
2 changed files with 124 additions and 14 deletions

View File

@@ -29,22 +29,67 @@ func NewCreatePostLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Create
func (l *CreatePostLogic) CreatePost(req *types.CreatePostReq) (resp *types.CreatePostResp, err error) {
var coverID sql.NullInt64
// If cover image key is provided, get the file ID from files table
// If cover image key is provided, move it from tmpfiles to files table
if req.CoverImageKey != "" {
query := `SELECT id FROM files WHERE file_key = $1`
err := l.svcCtx.DB.QueryRowContext(l.ctx, query, req.CoverImageKey).Scan(&coverID.Int64)
// Start a transaction
tx, err := l.svcCtx.DB.BeginTx(l.ctx, nil)
if err != nil {
l.Errorf("Failed to begin transaction: %v", err)
return nil, err
}
defer tx.Rollback()
// Get the tmpfile record
var fileName string
tmpQuery := `SELECT file_name FROM tmpfiles WHERE key = $1`
err = tx.QueryRowContext(l.ctx, tmpQuery, req.CoverImageKey).Scan(&fileName)
if err != nil {
if err == sql.ErrNoRows {
l.Errorf("Cover image file not found with key: %s", req.CoverImageKey)
l.Errorf("Cover image not found in tmpfiles with key: %s", req.CoverImageKey)
return nil, fmt.Errorf("cover image not found")
}
l.Errorf("Failed to get cover image file: %v", err)
l.Errorf("Failed to get tmpfile: %v", err)
return nil, err
}
// Insert into files table
fileQuery := `INSERT INTO files (file_name, file_key) VALUES ($1, $2) RETURNING id`
err = tx.QueryRowContext(l.ctx, fileQuery, fileName, req.CoverImageKey).Scan(&coverID.Int64)
if err != nil {
l.Errorf("Failed to insert file record: %v", err)
return nil, err
}
coverID.Valid = true
// Delete from tmpfiles
deleteQuery := `DELETE FROM tmpfiles WHERE key = $1`
_, err = tx.ExecContext(l.ctx, deleteQuery, req.CoverImageKey)
if err != nil {
l.Errorf("Failed to delete tmpfile: %v", err)
return nil, err
}
// Insert new post
var postID int64
postQuery := `INSERT INTO posts (title, content, cover_id) VALUES ($1, $2, $3) RETURNING id`
err = tx.QueryRowContext(l.ctx, postQuery, req.Title, req.Content, coverID).Scan(&postID)
if err != nil {
l.Errorf("Failed to create post: %v", err)
return nil, err
}
// Commit transaction
if err = tx.Commit(); err != nil {
l.Errorf("Failed to commit transaction: %v", err)
return nil, err
}
return &types.CreatePostResp{
PostId: fmt.Sprintf("%d", postID),
}, nil
}
// Insert new post
// No cover image - just insert the post
var postID int64
query := `INSERT INTO posts (title, content, cover_id) VALUES ($1, $2, $3) RETURNING id`
err = l.svcCtx.DB.QueryRowContext(l.ctx, query, req.Title, req.Content, coverID).Scan(&postID)