2024-06-25 12:13:24 +00:00
// HANDLERS FOR EMOJI FORMS AND EMOJI REACTIONS
// BELOW POSTS
2024-06-12 18:42:40 +00:00
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
2024-06-25 12:13:24 +00:00
emojiCounter , err := GetEmojis ( postId )
2024-06-12 18:42:40 +00:00
if err != nil {
2024-06-25 12:13:24 +00:00
c . AbortWithStatus ( http . StatusInternalServerError )
2024-06-12 18:42:40 +00:00
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-25 12:13:24 +00:00
c . AbortWithStatus ( http . StatusBadRequest )
2024-06-12 18:42:40 +00:00
}
// 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-25 12:13:24 +00:00
c . AbortWithStatus ( http . StatusInternalServerError )
2024-06-12 18:42:40 +00:00
}
// get emoji counts for each emoji
2024-06-25 12:13:24 +00:00
emojiCounter , err := GetEmojis ( reactedPostId )
2024-06-12 18:42:40 +00:00
if err != nil {
2024-06-25 12:13:24 +00:00
c . AbortWithStatus ( http . StatusInternalServerError )
2024-06-12 18:42:40 +00:00
}
// 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
2024-06-25 12:13:24 +00:00
func GetEmojis ( postId string ) ( map [ string ] int , error ) {
2024-06-12 18:42:40 +00:00
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
}