log101-dot-dev-services/handlers/emoji_form.go
2024-06-25 15:13:24 +03:00

79 lines
2.0 KiB
Go

// HANDLERS FOR EMOJI FORMS AND EMOJI REACTIONS
// BELOW POSTS
package handlers
import (
"errors"
"net/http"
"github.com/gin-gonic/gin"
"gorm.io/gorm/clause"
DB "log101-blog-services/db"
"log101-blog-services/models"
)
func GetEmojiForm(c *gin.Context) {
postId := c.Query("postId")
// get emoji counts for each emoji
emojiCounter, err := GetEmojis(postId)
if err != nil {
c.AbortWithStatus(http.StatusInternalServerError)
return
}
// Return the html template
c.HTML(http.StatusOK, "emoji_form.tmpl", gin.H{
"results": emojiCounter,
})
}
func PostEmojiForm(c *gin.Context) {
db := DB.GetDB()
reactedPostId := c.PostForm("postId")
reaction := c.PostForm("emojiInput")
// Check if parameters are missing
if reactedPostId == "" || reaction == "" {
c.AbortWithStatus(http.StatusBadRequest)
}
// Add the new emoji reaction to the database
result := db.Clauses(clause.OnConflict{
DoUpdates: clause.AssignmentColumns([]string{"emoji"}),
}).Create(&models.EmojiReaction{UserAnonIp: c.Request.RemoteAddr, Emoji: reaction, PostId: reactedPostId})
if result.Error != nil {
c.AbortWithStatus(http.StatusInternalServerError)
}
// get emoji counts for each emoji
emojiCounter, err := GetEmojis(reactedPostId)
if err != nil {
c.AbortWithStatus(http.StatusInternalServerError)
}
// Return the html with the updated emoji counter
c.HTML(http.StatusOK, "emoji_form.tmpl", gin.H{"results": emojiCounter})
}
// Get the emoji counts foe a given post id
func GetEmojis(postId string) (map[string]int, error) {
postReactions := []models.PostReaction{}
db := DB.GetDB()
// Get the emoji counts for each emoji
rows := db.Model(&models.EmojiReaction{}).Where("post_id = ?", postId).Select([]string{"emoji", "COUNT(*) as total_count"}).Group("emoji").Find(&postReactions)
if rows.Error != nil {
return nil, errors.New("couldn't get emoji counts")
}
// Transform rows to map
result := make(map[string]int)
for _, reaction := range postReactions {
result[reaction.Emoji] = reaction.TotalCount
}
return result, nil
}