All checks were successful
CI - Build and Push / Build and Push Docker Image (push) Successful in 53s
85 lines
2.2 KiB
Go
85 lines
2.2 KiB
Go
package logic
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"fmt"
|
|
|
|
"git.cialloo.com/CiallooWeb/Blog/app/internal/svc"
|
|
"git.cialloo.com/CiallooWeb/Blog/app/internal/types"
|
|
|
|
"github.com/zeromicro/go-zero/core/logx"
|
|
)
|
|
|
|
type DeletePostLogic struct {
|
|
logx.Logger
|
|
ctx context.Context
|
|
svcCtx *svc.ServiceContext
|
|
}
|
|
|
|
// Delete a blog post
|
|
func NewDeletePostLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeletePostLogic {
|
|
return &DeletePostLogic{
|
|
Logger: logx.WithContext(ctx),
|
|
ctx: ctx,
|
|
svcCtx: svcCtx,
|
|
}
|
|
}
|
|
|
|
func (l *DeletePostLogic) DeletePost(req *types.DeletePostReq) (resp *types.DeletePostResp, err error) {
|
|
// 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 cover_id before deleting the post
|
|
var coverID sql.NullInt64
|
|
getCoverQuery := `SELECT cover_id FROM posts WHERE id = $1`
|
|
err = tx.QueryRowContext(l.ctx, getCoverQuery, req.PostId).Scan(&coverID)
|
|
if err != nil {
|
|
if err == sql.ErrNoRows {
|
|
l.Errorf("Post not found with id: %s", req.PostId)
|
|
return nil, fmt.Errorf("post not found")
|
|
}
|
|
l.Errorf("Failed to get post: %v", err)
|
|
return nil, err
|
|
}
|
|
|
|
// Delete hashtag associations (post_hashtags will be deleted by CASCADE)
|
|
deleteHashtagsQuery := `DELETE FROM post_hashtags WHERE post_id = $1`
|
|
_, err = tx.ExecContext(l.ctx, deleteHashtagsQuery, req.PostId)
|
|
if err != nil {
|
|
l.Errorf("Failed to delete hashtag associations: %v", err)
|
|
return nil, err
|
|
}
|
|
|
|
// Delete post from database
|
|
deleteQuery := `DELETE FROM posts WHERE id = $1`
|
|
_, err = tx.ExecContext(l.ctx, deleteQuery, req.PostId)
|
|
if err != nil {
|
|
l.Errorf("Failed to delete post: %v", err)
|
|
return nil, err
|
|
}
|
|
|
|
// Delete cover file if exists
|
|
if coverID.Valid {
|
|
deleteFileQuery := `DELETE FROM files WHERE id = $1`
|
|
_, err = tx.ExecContext(l.ctx, deleteFileQuery, coverID.Int64)
|
|
if err != nil {
|
|
l.Errorf("Failed to delete cover file: %v", err)
|
|
// Don't fail the whole operation for this
|
|
}
|
|
}
|
|
|
|
// Commit transaction
|
|
if err = tx.Commit(); err != nil {
|
|
l.Errorf("Failed to commit transaction: %v", err)
|
|
return nil, err
|
|
}
|
|
|
|
return &types.DeletePostResp{}, nil
|
|
}
|