chore: add comments

This commit is contained in:
log101 2024-06-25 15:11:03 +03:00
parent 3f6cf095dc
commit 76279753e3
4 changed files with 10 additions and 6 deletions

View File

@ -28,6 +28,7 @@ func GetComments(c *gin.Context) {
return
}
// If there are no rows return empty response
if rows.RowsAffected == 0 {
c.AbortWithStatus(http.StatusNoContent)
return
@ -43,6 +44,7 @@ func PostComment(c *gin.Context) {
commentBody := c.PostForm("commentBody")
username := c.PostForm("username")
// post id and comment text is necessary
if postId == "" || commentBody == "" {
c.AbortWithStatus(http.StatusBadRequest)
return
@ -53,6 +55,7 @@ func PostComment(c *gin.Context) {
username = "anonim"
}
// save comment to database
result := db.Create(&models.Comment{Body: commentBody, PostId: postId, Username: username})
if result.Error != nil {
c.AbortWithStatus(http.StatusInternalServerError)

View File

@ -35,7 +35,7 @@ func TestGetEmojiForm(t *testing.T) {
func TestPostEmojiForm(t *testing.T) {
db := utils.SetupTestDB()
DB.SetDB(db) // Set the mock DB
DB.SetDB(db)
router := gin.Default()
router.LoadHTMLGlob("../templates/*")
@ -57,7 +57,7 @@ func TestPostEmojiForm(t *testing.T) {
func TestPostEmojiFormMissingParams(t *testing.T) {
db := utils.SetupTestDB()
DB.SetDB(db) // Set the mock DB
DB.SetDB(db)
router := gin.Default()
router.LoadHTMLGlob("../templates/*") // Ensure you have your templates in the right path
@ -77,7 +77,7 @@ func TestPostEmojiFormMissingParams(t *testing.T) {
func TestGetEmojis(t *testing.T) {
db := utils.SetupTestDB()
DB.SetDB(db) // Set the mock DB
DB.SetDB(db)
// Populate the test database with data
db.Create(&models.EmojiReaction{UserAnonIp: "127.0.0.2", Emoji: "😊", PostId: "1"})

View File

@ -44,7 +44,7 @@ func main() {
blog := r.Group("/api/blog/")
{
// Get the emoji form, you must provide postId query parameter
// Get the emoji form, postId query parameter is required
blog.GET("/forms/emoji", handlers.GetEmojiForm)
// Update the user's reaction to post, this handler will
@ -52,12 +52,11 @@ func main() {
// updates if user reacted before
blog.POST("/forms/emoji", handlers.PostEmojiForm)
// Get the comments for a given post id
// Get the comments for a post, postId query parameter is required
blog.GET("/comments", handlers.GetComments)
// Drop comment on a post, postId and comment body is required
blog.POST("/comments", handlers.PostComment)
}
r.Run(":8000")

View File

@ -7,12 +7,14 @@ import (
"gorm.io/gorm"
)
// Init in memory sql database for testing
func SetupTestDB() *gorm.DB {
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
if err != nil {
panic("failed to connect to in-memory database")
}
// create tables
db.AutoMigrate(&models.EmojiReaction{})
db.AutoMigrate(&models.Comment{})
return db