tailly_back_v2/internal/repository/comment_repository.go
2025-08-06 22:30:19 +03:00

113 lines
2.5 KiB
Go

package repository
import (
"context"
"database/sql"
"errors"
"tailly_back_v2/internal/domain"
)
var (
ErrCommentNotFound = errors.New("comment not found")
)
type CommentRepository interface {
Create(ctx context.Context, comment *domain.Comment) error
GetByID(ctx context.Context, id int) (*domain.Comment, error)
GetByPostID(ctx context.Context, postID int) ([]*domain.Comment, error)
Update(ctx context.Context, comment *domain.Comment) error
Delete(ctx context.Context, id int) error
GetCountComments(ctx context.Context, postID int) (int, error)
}
type commentRepository struct {
db *sql.DB
}
func (r *commentRepository) GetByID(ctx context.Context, id int) (*domain.Comment, error) {
//TODO implement me
panic("implement me")
}
func (r *commentRepository) Update(ctx context.Context, comment *domain.Comment) error {
//TODO implement me
panic("implement me")
}
func (r *commentRepository) Delete(ctx context.Context, id int) error {
//TODO implement me
panic("implement me")
}
func NewCommentRepository(db *sql.DB) *commentRepository {
return &commentRepository{db: db}
}
func (r *commentRepository) Create(ctx context.Context, comment *domain.Comment) error {
query := `
INSERT INTO comments (content, post_id, author_id, created_at, updated_at)
VALUES ($1, $2, $3, $4, $5)
RETURNING id
`
err := r.db.QueryRowContext(ctx, query,
comment.Content,
comment.PostID,
comment.AuthorID,
comment.CreatedAt,
comment.UpdatedAt,
).Scan(&comment.ID)
return err
}
func (r *commentRepository) GetByPostID(ctx context.Context, postID int) ([]*domain.Comment, error) {
query := `
SELECT id, content, post_id, author_id, created_at, updated_at
FROM comments
WHERE post_id = $1
ORDER BY created_at DESC
`
rows, err := r.db.QueryContext(ctx, query, postID)
if err != nil {
return nil, err
}
defer rows.Close()
var comments []*domain.Comment
for rows.Next() {
comment := &domain.Comment{}
err := rows.Scan(
&comment.ID,
&comment.Content,
&comment.PostID,
&comment.AuthorID,
&comment.CreatedAt,
&comment.UpdatedAt,
)
if err != nil {
return nil, err
}
comments = append(comments, comment)
}
return comments, nil
}
func (r *commentRepository) GetCountComments(ctx context.Context, postID int) (int, error) {
query := `
SELECT COUNT(*) as comment_count
FROM comments
WHERE post_id = $1
`
var count int
err := r.db.QueryRowContext(ctx, query, postID).Scan(&count)
if err != nil {
return 0, err
}
return count, nil
}