log101-dot-dev-services/handlers/emoji_form.go

79 lines
2.2 KiB
Go
Raw Normal View History

// 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.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 == "" {
2024-06-18 18:36:30 +00:00
c.HTML(http.StatusBadRequest, "emoji_form_error.tmpl", gin.H{"errorMessage": "missing parameters"})
}
// 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 {
2024-06-12 19:21:53 +00:00
c.HTML(http.StatusOK, "emoji_form_error.tmpl", gin.H{"errorMessage": "error writing to database"})
}
// get emoji counts for each emoji
emojiCounter, err := GetEmojis(reactedPostId)
if err != nil {
2024-06-12 19:21:53 +00:00
c.HTML(http.StatusOK, "emoji_form_error.tmpl", gin.H{"errorMessage": "error getting the emoji counts"})
}
// 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
}