Skip to content

Commit

Permalink
Implemented Vote pg repo
Browse files Browse the repository at this point in the history
  • Loading branch information
darleet committed May 28, 2024
1 parent 8e8d0b7 commit a9ed5f2
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 1 deletion.
2 changes: 1 addition & 1 deletion cmd/server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ func main() {

articles := article.NewUsecase(repo)
comments := comment.NewUsecase(repo)
votes := vote.NewUsecase(nil)
votes := vote.NewUsecase(repo)
users := user.NewUsecase()

res := resolver.NewRootResolvers(log, articles, comments, users, votes)
Expand Down
55 changes: 55 additions & 0 deletions internal/repository/pg/vote.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package pg

import (
"context"
"fmt"
"github.com/darleet/blog-graphql/internal/model"
"github.com/darleet/blog-graphql/pkg/errors"
)

func parseValue(value model.VoteValue) int {
switch value {
case model.VoteValueUp:
return 1
case model.VoteValueDown:
return -1
default:
return 0
}
}

func (r *Repository) SetArticleVote(ctx context.Context, userID string, input model.VoteArticle) (int, error) {
q := `
INSERT INTO articles_votes (article_id, author_id, value) VALUES ($1, $2, $3)
ON CONFLICT (article_id, author_id) DO UPDATE SET value = $3
RETURNING (SELECT COALESCE(SUM(value), 0) FROM articles_votes WHERE article_id = $1)
`

value := parseValue(input.Value)

var votes int
err := r.pool.QueryRow(ctx, q, input.ArticleID, userID, value).Scan(&votes)

if err != nil {
return 0, errors.NewInternalServerError(fmt.Errorf("VoteRepository.SetArticleVote: %w", err))
}
return votes, nil
}

func (r *Repository) SetCommentVote(ctx context.Context, userID string, input model.VoteComment) (int, error) {
q := `
INSERT INTO comments_votes (comment_id, author_id, value) VALUES ($1, $2, $3)
ON CONFLICT (comment_id, author_id) DO UPDATE SET value = $3
RETURNING (SELECT COALESCE(SUM(value), 0) FROM comments_votes WHERE comment_id = $1)
`

value := parseValue(input.Value)

var votes int
err := r.pool.QueryRow(ctx, q, input.CommentID, userID, value).Scan(&votes)

if err != nil {
return 0, errors.NewInternalServerError(fmt.Errorf("VoteRepository.SetCommentVote: %w", err))
}
return votes, nil
}

0 comments on commit a9ed5f2

Please sign in to comment.