All checks were successful
CI - Build and Push / Build and Push Docker Image (push) Successful in 53s
60 lines
1.5 KiB
Go
60 lines
1.5 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 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, get the file ID from 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)
|
|
if err != nil {
|
|
if err == sql.ErrNoRows {
|
|
l.Errorf("Cover image file not found with key: %s", req.CoverImageKey)
|
|
return nil, fmt.Errorf("cover image not found")
|
|
}
|
|
l.Errorf("Failed to get cover image file: %v", err)
|
|
return nil, err
|
|
}
|
|
coverID.Valid = true
|
|
}
|
|
|
|
// Insert new 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
|
|
}
|