Files
gobeyhan/app/blog/services/comment_service.go
Beyhan Oğur f34e54c5a5 first commit
2026-04-26 21:43:40 +03:00

116 lines
2.7 KiB
Go

package services
import (
"errors"
"gobeyhan/database"
"gobeyhan/database/models"
"gorm.io/gorm"
)
type CommentService struct{}
func NewCommentService() *CommentService {
return &CommentService{}
}
// GetCommentsByPost retrieves comments for a specific post
func (s *CommentService) GetCommentsByPost(postID uint64, activeOnly bool) ([]models.Comment, error) {
var comments []models.Comment
query := database.DB.
Where("product_id = ?", postID).
Preload("Parent").
Preload("Children")
if activeOnly {
query = query.Where("is_active = ?", true)
}
err := query.Order("created_at DESC").Find(&comments).Error
return comments, err
}
// GetAllComments retrieves all comments with pagination
func (s *CommentService) GetAllComments(page, limit int, activeOnly bool) ([]models.Comment, int64, error) {
var comments []models.Comment
var total int64
query := database.DB.
Preload("Product").
Preload("Parent").
Preload("Children")
if activeOnly {
query = query.Where("is_active = ?", true)
}
query.Model(&models.Comment{}).Count(&total)
err := query.
Offset((page - 1) * limit).
Limit(limit).
Order("created_at DESC").
Find(&comments).Error
return comments, total, err
}
// GetCommentByID retrieves a comment by ID
func (s *CommentService) GetCommentByID(id uint64) (*models.Comment, error) {
var comment models.Comment
err := database.DB.
Preload("Product").
Preload("Parent").
Preload("Children").
First(&comment, id).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, nil
}
return nil, err
}
return &comment, nil
}
// CreateComment creates a new comment
func (s *CommentService) CreateComment(comment *models.Comment) error {
return database.DB.Create(comment).Error
}
// UpdateComment updates an existing comment
func (s *CommentService) UpdateComment(id uint64, updates map[string]interface{}) error {
result := database.DB.Model(&models.Comment{}).Where("id = ?", id).Updates(updates)
if result.Error != nil {
return result.Error
}
if result.RowsAffected == 0 {
return gorm.ErrRecordNotFound
}
return nil
}
// DeleteComment deletes a comment by ID
func (s *CommentService) DeleteComment(id uint64) error {
result := database.DB.Delete(&models.Comment{}, id)
if result.Error != nil {
return result.Error
}
if result.RowsAffected == 0 {
return gorm.ErrRecordNotFound
}
return nil
}
// GetCommentReplies retrieves replies to a specific comment
func (s *CommentService) GetCommentReplies(commentID uint64) ([]models.Comment, error) {
var replies []models.Comment
err := database.DB.
Where("parent_id = ? AND is_active = ?", commentID, true).
Order("created_at ASC").
Find(&replies).Error
return replies, err
}