This repository has been archived on 2021-09-01. You can view files and clone it, but cannot push or open issues or pull requests.
goddit/postgres/comment_store.go

59 lines
1.5 KiB
Go
Raw Normal View History

package postgres
import (
"fmt"
"git.snrd.de/Spaenny/goddit"
"github.com/google/uuid"
"github.com/jmoiron/sqlx"
)
type CommentStore struct {
*sqlx.DB
}
func (s *CommentStore) Comment(id uuid.UUID) (goddit.Comment, error) {
var c goddit.Comment
if err := s.Get(&c, `SELECT * FROM comments WHERE id = $1`, id); err != nil {
return goddit.Comment{}, fmt.Errorf("error getting comment: %w", err)
}
return c, nil
}
func (s *CommentStore) CommentsByPost(postID uuid.UUID) ([]goddit.Comment, error) {
var cc []goddit.Comment
if err := s.Select(&cc, `SELECT * FROM comments WHERE post_id = $1 ORDER BY votes DESC`, postID); err != nil {
return []goddit.Comment{}, fmt.Errorf("error getting comments: %w", err)
}
return cc, nil
}
func (s *CommentStore) CreateComment(c *goddit.Comment) error {
if err := s.Get(c, `INSERT INTO comments VALUES($1, $2, $3, $4) RETURNING *`,
c.ID,
c.PostID,
c.Content,
c.Votes); err != nil {
return fmt.Errorf("error creating comment: %w", err)
}
return nil
}
func (s *CommentStore) UpdateComment(c *goddit.Comment) error {
if err := s.Get(c, `UPDATE comments SET post_id = $1, content = $2, votes = $3 WHERE id = $4 RETURNING *`,
c.PostID,
c.Content,
c.Votes,
c.ID); err != nil {
return fmt.Errorf("error updating comments: %w", err)
}
return nil
}
func (s *CommentStore) DeleteComment(id uuid.UUID) error {
if _, err := s.Exec(`DELETE FROM comments WHERE id = $1`, id); err != nil {
return fmt.Errorf("error deleting comment: %w", err)
}
return nil
}