80 lines
2.1 KiB
Go
80 lines
2.1 KiB
Go
|
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 := CountEmojis(postId)
|
||
|
if err != nil {
|
||
|
c.HTML(http.StatusOK, "emoji_form.tmpl", gin.H{"error": "error getting the emoji counts"})
|
||
|
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.HTML(http.StatusOK, "emoji_form.tmpl", gin.H{"error": "missing parameters"})
|
||
|
return
|
||
|
}
|
||
|
|
||
|
// 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.HTML(http.StatusOK, "emoji_form.tmpl", gin.H{"error": "error writing to database"})
|
||
|
return
|
||
|
}
|
||
|
|
||
|
// get emoji counts for each emoji
|
||
|
emojiCounter, err := CountEmojis(reactedPostId)
|
||
|
if err != nil {
|
||
|
c.HTML(http.StatusOK, "emoji_form.tmpl", gin.H{"error": "error getting the emoji counts"})
|
||
|
return
|
||
|
}
|
||
|
|
||
|
// 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 CountEmojis(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
|
||
|
}
|