Skip to content

Commit

Permalink
feat(controllers/reward.SetComment): init
Browse files Browse the repository at this point in the history
  • Loading branch information
Prince213 committed Apr 26, 2024
1 parent fdf8fb7 commit 53617be
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 0 deletions.
1 change: 1 addition & 0 deletions internal/controllers/reward.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,5 @@ import (
func RewardRoutes(r fiber.Router) {
route := r.Group("/reward")
route.Get("/ranklist", reward.Ranklist)
route.Post("/set/:id", reward.SetComment)
}
71 changes: 71 additions & 0 deletions internal/controllers/reward/setcomment.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package reward

import (
"coursebench-backend/internal/middlewares/session"
"coursebench-backend/pkg/database"
"coursebench-backend/pkg/errors"
"coursebench-backend/pkg/models"
"coursebench-backend/pkg/queries"
"strconv"

"github.com/gofiber/fiber/v2"
"gorm.io/gorm"
)

type SetCommentRequest struct {
Reward int `json:"reward"`
}

func SetComment(c *fiber.Ctx) error {
c.Accepts("application/json")
var request SetCommentRequest
if err := c.BodyParser(&request); err != nil {
return errors.Wrap(err, errors.InvalidArgument)
}

idRaw := c.Params("id", "GG")
id, err := strconv.Atoi(idRaw)
if err != nil {
return errors.New(errors.InvalidArgument)
}

uid, err := session.GetUserID(c)
if err != nil {
uid = 0
}

db := database.GetDB()
user, err := queries.GetUserByID(db, uid)
if err != nil {
return errors.Wrap(err, errors.DatabaseError)
}
if !(user.IsCommunityAdmin || user.IsAdmin) {
return errors.New(errors.PermissionDenied)
}

comment := &models.Comment{}
result := db.First(&comment, id)
if result.Error != nil {
return errors.Wrap(result.Error, errors.DatabaseError)
}

comment.User.Reward -= comment.Reward
comment.Reward = request.Reward
comment.User.Reward += comment.Reward

if err := db.Transaction(func(tx *gorm.DB) error {
if err := tx.Save(comment).Error; err != nil {
return err
}
if err := tx.Save(user).Error; err != nil {
return err
}
return nil
}); err != nil {
return errors.Wrap(err, errors.DatabaseError)
}

return c.Status(fiber.StatusOK).JSON(models.OKResponse{
Error: false,
})
}

0 comments on commit 53617be

Please sign in to comment.