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 CreatePostLogic struct { logx.Logger ctx context.Context svcCtx *svc.ServiceContext } // Create a new blog post func NewCreatePostLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreatePostLogic { return &CreatePostLogic{ Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx, } } func (l *CreatePostLogic) CreatePost(req *types.CreatePostReq) (resp *types.CreatePostResp, err error) { var coverID sql.NullInt64 // If cover image key is provided, move it from tmpfiles to files table if req.CoverImageKey != "" { // 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 not found in tmpfiles with key: %s", req.CoverImageKey) return nil, fmt.Errorf("cover image not found") } 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 } // 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) if err != nil { l.Errorf("Failed to create post: %v", err) return nil, err } return &types.CreatePostResp{ PostId: fmt.Sprintf("%d", postID), }, nil }