From 2b89b90fc5f48b0d74a305ff913ec607091a7e96 Mon Sep 17 00:00:00 2001 From: log101 Date: Sun, 16 Jun 2024 20:52:08 +0300 Subject: [PATCH 1/7] ci: add test stage to dockerfile --- Dockerfile | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Dockerfile b/Dockerfile index d2cdeeb..b6454eb 100644 --- a/Dockerfile +++ b/Dockerfile @@ -9,6 +9,8 @@ RUN go mod download && go mod verify COPY . . RUN go build -v -o log101-dot-dev-services +RUN go test -v ./... + FROM alpine WORKDIR /root/app COPY --from=builder /usr/src/app . From 14e3bed6bb141d871a35192dc50c77ba83908656 Mon Sep 17 00:00:00 2001 From: log101 Date: Tue, 18 Jun 2024 21:36:30 +0300 Subject: [PATCH 2/7] feat: add endpoints --- handlers/emoji_form.go | 5 +--- main.go | 41 ++++++++++++++++++++++++++++++--- models/Comment.go | 8 +++++++ templates/comment_form.tmpl | 11 +++++++++ templates/emoji_form.tmpl | 12 +++++----- templates/emoji_form_error.tmpl | 12 +++++----- 6 files changed, 70 insertions(+), 19 deletions(-) create mode 100644 models/Comment.go create mode 100644 templates/comment_form.tmpl diff --git a/handlers/emoji_form.go b/handlers/emoji_form.go index 3be3824..d5746ee 100644 --- a/handlers/emoji_form.go +++ b/handlers/emoji_form.go @@ -34,8 +34,7 @@ func PostEmojiForm(c *gin.Context) { // Check if parameters are missing if reactedPostId == "" || reaction == "" { - c.HTML(http.StatusOK, "emoji_form_error.tmpl", gin.H{"errorMessage": "missing parameters"}) - return + c.HTML(http.StatusBadRequest, "emoji_form_error.tmpl", gin.H{"errorMessage": "missing parameters"}) } // Add the new emoji reaction to the database @@ -44,14 +43,12 @@ func PostEmojiForm(c *gin.Context) { }).Create(&models.EmojiReaction{UserAnonIp: c.Request.RemoteAddr, Emoji: reaction, PostId: reactedPostId}) if result.Error != nil { c.HTML(http.StatusOK, "emoji_form_error.tmpl", gin.H{"errorMessage": "error writing to database"}) - return } // get emoji counts for each emoji emojiCounter, err := CountEmojis(reactedPostId) if err != nil { c.HTML(http.StatusOK, "emoji_form_error.tmpl", gin.H{"errorMessage": "error getting the emoji counts"}) - return } // Return the html with the updated emoji counter diff --git a/main.go b/main.go index 03e5be1..ec78442 100644 --- a/main.go +++ b/main.go @@ -2,6 +2,7 @@ package main import ( "log" + "net/http" "github.com/gin-contrib/cors" "github.com/gin-gonic/gin" @@ -11,6 +12,7 @@ import ( DB "log101-blog-services/db" "log101-blog-services/handlers" "log101-blog-services/middleware" + "log101-blog-services/models" ) func main() { @@ -42,15 +44,48 @@ func main() { r.Use(cors.New(corsConfig)) r.Use(middleware.AnonymizeIPMiddleware()) - blogForm := r.Group("/blog/api/") + blog := r.Group("/api/blog/") { // Get the emoji form, you must provide postId query parameter - blogForm.GET("/forms/emoji", handlers.GetEmojiForm) + blog.GET("/forms/emoji", handlers.GetEmojiForm) // Update the user's reaction to post, this handler will // add a new entry to the database with anonymized ip // updates if user reacted before - blogForm.POST("/forms/emoji/post", handlers.PostEmojiForm) + blog.POST("/forms/emoji", handlers.PostEmojiForm) + + blog.GET("/comments", func(c *gin.Context) { + db := DB.GetDB() + postId := c.Query("postId") + comments := []models.Comment{} + + rows := db.Where("post_id = ?", postId).Find(&comments) + + if rows.Error != nil { + c.HTML(http.StatusInternalServerError, "comment_form.tmpl", gin.H{"errorMessage": "error getting comments", "comments": comments}) + } + + c.HTML(http.StatusOK, "comment_form.tmpl", gin.H{"errorMessage": "error getting comments", "comments": comments}) + }) + + blog.POST("/comments", func(c *gin.Context) { + db := DB.GetDB() + postId := c.PostForm("postId") + commentBody := c.PostForm("commentBody") + username := c.PostForm("username") + + if postId == "" || commentBody == "" { + c.HTML(http.StatusBadRequest, "comment_form.tmpl", gin.H{}) + } + + result := db.Create(&models.Comment{Body: commentBody, PostId: postId, Username: username}) + if result.Error != nil { + c.HTML(http.StatusInternalServerError, "comment_form.tmpl", gin.H{}) + } + + c.HTML(http.StatusOK, "comment_form.tmpl", gin.H{}) + }) + } r.Run(":8000") diff --git a/models/Comment.go b/models/Comment.go new file mode 100644 index 0000000..6f5cc50 --- /dev/null +++ b/models/Comment.go @@ -0,0 +1,8 @@ +package models + +// Gorm model +type Comment struct { + Body string + PostId string + Username string +} diff --git a/templates/comment_form.tmpl b/templates/comment_form.tmpl new file mode 100644 index 0000000..54227e8 --- /dev/null +++ b/templates/comment_form.tmpl @@ -0,0 +1,11 @@ +
+

+ Arafat Candan +

+ +

+ Daha önce hiç bu açıdan bakmamıştım, harika bir yazı olmuş. +

+
diff --git a/templates/emoji_form.tmpl b/templates/emoji_form.tmpl index 32672e2..a74ce72 100644 --- a/templates/emoji_form.tmpl +++ b/templates/emoji_form.tmpl @@ -1,9 +1,9 @@
- - - - - - + + + + + +
diff --git a/templates/emoji_form_error.tmpl b/templates/emoji_form_error.tmpl index 3d9a8c1..d8be0fd 100644 --- a/templates/emoji_form_error.tmpl +++ b/templates/emoji_form_error.tmpl @@ -1,9 +1,9 @@
- - - - - - + + + + + +

{{ .errorMessage }}

From 0bc4325102854ca55b6b488edf1ae9635f1f78a3 Mon Sep 17 00:00:00 2001 From: log101 Date: Wed, 19 Jun 2024 16:42:43 +0300 Subject: [PATCH 3/7] feat: add templates --- db/db.go | 1 + main.go | 23 ++++++++++++------- templates/{comment_form.tmpl => comment.tmpl} | 4 ++-- templates/comments.tmpl | 3 +++ 4 files changed, 21 insertions(+), 10 deletions(-) rename templates/{comment_form.tmpl => comment.tmpl} (72%) create mode 100644 templates/comments.tmpl diff --git a/db/db.go b/db/db.go index b6cadf0..f2b295c 100644 --- a/db/db.go +++ b/db/db.go @@ -20,6 +20,7 @@ func InitDB() { } db.AutoMigrate(&models.EmojiReaction{}) + db.AutoMigrate(&models.Comment{}) } func GetDB() *gorm.DB { diff --git a/main.go b/main.go index ec78442..f859a4a 100644 --- a/main.go +++ b/main.go @@ -59,13 +59,18 @@ func main() { postId := c.Query("postId") comments := []models.Comment{} - rows := db.Where("post_id = ?", postId).Find(&comments) - - if rows.Error != nil { - c.HTML(http.StatusInternalServerError, "comment_form.tmpl", gin.H{"errorMessage": "error getting comments", "comments": comments}) + if postId == "" { + c.AbortWithStatus(http.StatusBadRequest) + return } - c.HTML(http.StatusOK, "comment_form.tmpl", gin.H{"errorMessage": "error getting comments", "comments": comments}) + rows := db.Where("post_id = ?", postId).Find(&comments) + if rows.Error != nil { + c.AbortWithStatus(http.StatusInternalServerError) + return + } + + c.HTML(http.StatusOK, "comments.tmpl", gin.H{"Comments": comments}) }) blog.POST("/comments", func(c *gin.Context) { @@ -75,15 +80,17 @@ func main() { username := c.PostForm("username") if postId == "" || commentBody == "" { - c.HTML(http.StatusBadRequest, "comment_form.tmpl", gin.H{}) + c.AbortWithStatus(http.StatusBadRequest) + return } result := db.Create(&models.Comment{Body: commentBody, PostId: postId, Username: username}) if result.Error != nil { - c.HTML(http.StatusInternalServerError, "comment_form.tmpl", gin.H{}) + c.AbortWithStatus(http.StatusInternalServerError) + return } - c.HTML(http.StatusOK, "comment_form.tmpl", gin.H{}) + c.HTML(http.StatusOK, "comment.tmpl", gin.H{"Username": username, "Body": commentBody}) }) } diff --git a/templates/comment_form.tmpl b/templates/comment.tmpl similarity index 72% rename from templates/comment_form.tmpl rename to templates/comment.tmpl index 54227e8..067ca4d 100644 --- a/templates/comment_form.tmpl +++ b/templates/comment.tmpl @@ -2,10 +2,10 @@

- Arafat Candan + {{ .Username }}

- Daha önce hiç bu açıdan bakmamıştım, harika bir yazı olmuş. + {{ .Body }}

diff --git a/templates/comments.tmpl b/templates/comments.tmpl new file mode 100644 index 0000000..ad768ad --- /dev/null +++ b/templates/comments.tmpl @@ -0,0 +1,3 @@ +{{ range .Comments }} + {{ template "comment.tmpl" . }} +{{ end }} From 8adfa22c9dae06e5ac14abd2315ff3ea0b10852e Mon Sep 17 00:00:00 2001 From: log101 Date: Thu, 20 Jun 2024 19:40:38 +0300 Subject: [PATCH 4/7] refactor: extract comment handlers to a seperate file --- handlers/comment.go | 63 +++++++++++++++++++++++++++++++++++++ handlers/emoji_form.go | 8 +++-- handlers/emoji_form_test.go | 6 ++-- main.go | 43 +++---------------------- 4 files changed, 75 insertions(+), 45 deletions(-) create mode 100644 handlers/comment.go diff --git a/handlers/comment.go b/handlers/comment.go new file mode 100644 index 0000000..b9e7ccd --- /dev/null +++ b/handlers/comment.go @@ -0,0 +1,63 @@ +// HANDLERS FOR COMMENTING ON POSTS +package handlers + +import ( + "net/http" + + "github.com/gin-gonic/gin" + + DB "log101-blog-services/db" + "log101-blog-services/models" +) + +func GetComments(c *gin.Context) { + db := DB.GetDB() + postId := c.Query("postId") + comments := []models.Comment{} + + // Post id is required + if postId == "" { + c.AbortWithStatus(http.StatusBadRequest) + return + } + + // Retrieve comments related to post + rows := db.Where("post_id = ?", postId).Find(&comments) + if rows.Error != nil { + c.AbortWithStatus(http.StatusInternalServerError) + return + } + + if rows.RowsAffected == 0 { + c.AbortWithStatus(http.StatusNoContent) + return + } else { + c.HTML(http.StatusOK, "comments.tmpl", gin.H{"Comments": comments}) + } + +} + +func PostComment(c *gin.Context) { + db := DB.GetDB() + postId := c.PostForm("postId") + commentBody := c.PostForm("commentBody") + username := c.PostForm("username") + + if postId == "" || commentBody == "" { + c.AbortWithStatus(http.StatusBadRequest) + return + } + + // username is anonymous if not present + if username == "" { + username = "anonim" + } + + result := db.Create(&models.Comment{Body: commentBody, PostId: postId, Username: username}) + if result.Error != nil { + c.AbortWithStatus(http.StatusInternalServerError) + return + } + + c.HTML(http.StatusOK, "comment.tmpl", gin.H{"Username": username, "Body": commentBody}) +} diff --git a/handlers/emoji_form.go b/handlers/emoji_form.go index d5746ee..d71d01f 100644 --- a/handlers/emoji_form.go +++ b/handlers/emoji_form.go @@ -1,3 +1,5 @@ +// HANDLERS FOR EMOJI FORMS AND EMOJI REACTIONS +// BELOW POSTS package handlers import ( @@ -15,7 +17,7 @@ func GetEmojiForm(c *gin.Context) { postId := c.Query("postId") // get emoji counts for each emoji - emojiCounter, err := CountEmojis(postId) + emojiCounter, err := GetEmojis(postId) if err != nil { c.HTML(http.StatusOK, "emoji_form.tmpl", gin.H{"error": "error getting the emoji counts"}) return @@ -46,7 +48,7 @@ func PostEmojiForm(c *gin.Context) { } // get emoji counts for each emoji - emojiCounter, err := CountEmojis(reactedPostId) + emojiCounter, err := GetEmojis(reactedPostId) if err != nil { c.HTML(http.StatusOK, "emoji_form_error.tmpl", gin.H{"errorMessage": "error getting the emoji counts"}) } @@ -56,7 +58,7 @@ func PostEmojiForm(c *gin.Context) { } // Get the emoji counts foe a given post id -func CountEmojis(postId string) (map[string]int, error) { +func GetEmojis(postId string) (map[string]int, error) { postReactions := []models.PostReaction{} db := DB.GetDB() diff --git a/handlers/emoji_form_test.go b/handlers/emoji_form_test.go index e89bfec..b74727f 100644 --- a/handlers/emoji_form_test.go +++ b/handlers/emoji_form_test.go @@ -83,11 +83,11 @@ func TestPostEmojiFormMissingParams(t *testing.T) { w := httptest.NewRecorder() router.ServeHTTP(w, req) - assert.Equal(t, http.StatusOK, w.Code) + assert.Equal(t, http.StatusBadRequest, w.Code) assert.Contains(t, w.Body.String(), "missing parameters") } -func TestCountEmojis(t *testing.T) { +func TestGetEmojis(t *testing.T) { db := SetupTestDB() DB.SetDB(db) // Set the mock DB @@ -95,7 +95,7 @@ func TestCountEmojis(t *testing.T) { db.Create(&models.EmojiReaction{UserAnonIp: "127.0.0.2", Emoji: "😊", PostId: "1"}) db.Create(&models.EmojiReaction{UserAnonIp: "127.0.0.1", Emoji: "😂", PostId: "1"}) - counts, err := CountEmojis("1") + counts, err := GetEmojis("1") assert.NoError(t, err) assert.Equal(t, 1, counts["😊"]) assert.Equal(t, 1, counts["😂"]) diff --git a/main.go b/main.go index f859a4a..f106334 100644 --- a/main.go +++ b/main.go @@ -2,7 +2,6 @@ package main import ( "log" - "net/http" "github.com/gin-contrib/cors" "github.com/gin-gonic/gin" @@ -12,7 +11,6 @@ import ( DB "log101-blog-services/db" "log101-blog-services/handlers" "log101-blog-services/middleware" - "log101-blog-services/models" ) func main() { @@ -54,44 +52,11 @@ func main() { // updates if user reacted before blog.POST("/forms/emoji", handlers.PostEmojiForm) - blog.GET("/comments", func(c *gin.Context) { - db := DB.GetDB() - postId := c.Query("postId") - comments := []models.Comment{} + // Get the comments for a given post id + blog.GET("/comments", handlers.GetComments) - if postId == "" { - c.AbortWithStatus(http.StatusBadRequest) - return - } - - rows := db.Where("post_id = ?", postId).Find(&comments) - if rows.Error != nil { - c.AbortWithStatus(http.StatusInternalServerError) - return - } - - c.HTML(http.StatusOK, "comments.tmpl", gin.H{"Comments": comments}) - }) - - blog.POST("/comments", func(c *gin.Context) { - db := DB.GetDB() - postId := c.PostForm("postId") - commentBody := c.PostForm("commentBody") - username := c.PostForm("username") - - if postId == "" || commentBody == "" { - c.AbortWithStatus(http.StatusBadRequest) - return - } - - result := db.Create(&models.Comment{Body: commentBody, PostId: postId, Username: username}) - if result.Error != nil { - c.AbortWithStatus(http.StatusInternalServerError) - return - } - - c.HTML(http.StatusOK, "comment.tmpl", gin.H{"Username": username, "Body": commentBody}) - }) + // Drop comment on a post, postId and comment body is required + blog.POST("/comments", handlers.PostComment) } From 84119e32c5b4db45392fd9c72eb682c1a60c9764 Mon Sep 17 00:00:00 2001 From: log101 Date: Tue, 25 Jun 2024 14:52:06 +0300 Subject: [PATCH 5/7] test: add tests for comments --- handlers/comment_test.go | 106 ++++++++++++++++++++++++++++++++++++ handlers/emoji_form_test.go | 23 ++------ utils/main.go | 19 +++++++ 3 files changed, 131 insertions(+), 17 deletions(-) create mode 100644 handlers/comment_test.go create mode 100644 utils/main.go diff --git a/handlers/comment_test.go b/handlers/comment_test.go new file mode 100644 index 0000000..5ff8cff --- /dev/null +++ b/handlers/comment_test.go @@ -0,0 +1,106 @@ +package handlers + +import ( + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" + + "github.com/gin-gonic/gin" + + "github.com/stretchr/testify/assert" + + DB "log101-blog-services/db" + "log101-blog-services/models" + "log101-blog-services/utils" +) + +func TestGetComments(t *testing.T) { + db := utils.SetupTestDB() + DB.SetDB(db) + + router := gin.Default() + router.LoadHTMLGlob("../templates/*") + + // Populate the test database with data + // Create a comment with a username + db.Create(&models.Comment{PostId: "1", Body: "sample body 1", Username: "username1"}) + db.Create(&models.Comment{PostId: "1", Body: "sample body 2", Username: "username2"}) + + router.GET("/comments", GetComments) + + req, _ := http.NewRequest("GET", "/comments?postId=1", nil) + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + + assert.Equal(t, http.StatusOK, w.Code) + assert.Contains(t, w.Body.String(), "sample body 1") + assert.Contains(t, w.Body.String(), "sample body 2") +} + +func TestPostComment(t *testing.T) { + db := utils.SetupTestDB() + DB.SetDB(db) // Set the mock DB + + router := gin.Default() + router.LoadHTMLGlob("../templates/*") + + router.POST("/comments", PostComment) + + form := url.Values{} + form.Add("postId", "1") + form.Add("commentBody", "sample comment 1") + form.Add("username", "username1") + + req, _ := http.NewRequest("POST", "/comments", strings.NewReader(form.Encode())) + req.Header.Add("Content-Type", "application/x-www-form-urlencoded") + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + + assert.Equal(t, http.StatusOK, w.Code) + assert.Contains(t, w.Body.String(), "sample comment 1") +} + +func TestPostAnonymousComment(t *testing.T) { + db := utils.SetupTestDB() + DB.SetDB(db) // Set the mock DB + + router := gin.Default() + router.LoadHTMLGlob("../templates/*") + + router.POST("/comments", PostComment) + + form := url.Values{} + form.Add("postId", "1") + form.Add("commentBody", "sample comment 1") + + req, _ := http.NewRequest("POST", "/comments", strings.NewReader(form.Encode())) + req.Header.Add("Content-Type", "application/x-www-form-urlencoded") + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + + assert.Equal(t, http.StatusOK, w.Code) + assert.Contains(t, w.Body.String(), "sample comment 1") + assert.Contains(t, w.Body.String(), "anonim") +} + +func TestPostCommentMissingParams(t *testing.T) { + db := utils.SetupTestDB() + DB.SetDB(db) // Set the mock DB + + router := gin.Default() + router.LoadHTMLGlob("../templates/*") // Ensure you have your templates in the right path + + router.POST("/comments", PostComment) + + form := url.Values{} + form.Add("postId", "1") + + req, _ := http.NewRequest("POST", "/comments", strings.NewReader(form.Encode())) + req.Header.Add("Content-Type", "application/x-www-form-urlencoded") + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + + assert.Equal(t, http.StatusBadRequest, w.Code) +} diff --git a/handlers/emoji_form_test.go b/handlers/emoji_form_test.go index b74727f..ea80537 100644 --- a/handlers/emoji_form_test.go +++ b/handlers/emoji_form_test.go @@ -8,30 +8,19 @@ import ( "testing" "github.com/gin-gonic/gin" - "github.com/glebarez/sqlite" "github.com/stretchr/testify/assert" - "gorm.io/gorm" DB "log101-blog-services/db" "log101-blog-services/models" + "log101-blog-services/utils" ) -func SetupTestDB() *gorm.DB { - db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{}) - if err != nil { - panic("failed to connect to in-memory database") - } - - db.AutoMigrate(&models.EmojiReaction{}) - return db -} - func TestGetEmojiForm(t *testing.T) { - db := SetupTestDB() + db := utils.SetupTestDB() DB.SetDB(db) router := gin.Default() - router.LoadHTMLGlob("../templates/*") // Ensure you have your templates in the right path + router.LoadHTMLGlob("../templates/*") router.GET("/emoji_form", GetEmojiForm) @@ -45,7 +34,7 @@ func TestGetEmojiForm(t *testing.T) { } func TestPostEmojiForm(t *testing.T) { - db := SetupTestDB() + db := utils.SetupTestDB() DB.SetDB(db) // Set the mock DB router := gin.Default() @@ -67,7 +56,7 @@ func TestPostEmojiForm(t *testing.T) { } func TestPostEmojiFormMissingParams(t *testing.T) { - db := SetupTestDB() + db := utils.SetupTestDB() DB.SetDB(db) // Set the mock DB router := gin.Default() @@ -88,7 +77,7 @@ func TestPostEmojiFormMissingParams(t *testing.T) { } func TestGetEmojis(t *testing.T) { - db := SetupTestDB() + db := utils.SetupTestDB() DB.SetDB(db) // Set the mock DB // Populate the test database with data diff --git a/utils/main.go b/utils/main.go new file mode 100644 index 0000000..45020c8 --- /dev/null +++ b/utils/main.go @@ -0,0 +1,19 @@ +package utils + +import ( + "log101-blog-services/models" + + "github.com/glebarez/sqlite" + "gorm.io/gorm" +) + +func SetupTestDB() *gorm.DB { + db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{}) + if err != nil { + panic("failed to connect to in-memory database") + } + + db.AutoMigrate(&models.EmojiReaction{}) + db.AutoMigrate(&models.Comment{}) + return db +} From 3f6cf095dc372fef3ae405490ecc5a9d8a832497 Mon Sep 17 00:00:00 2001 From: log101 Date: Tue, 25 Jun 2024 15:04:20 +0300 Subject: [PATCH 6/7] feat: abort with status instead of returning html on erros --- handlers/emoji_form.go | 8 ++++---- handlers/emoji_form_test.go | 1 - templates/emoji_form.tmpl | 2 +- templates/emoji_form_error.tmpl | 9 --------- 4 files changed, 5 insertions(+), 15 deletions(-) delete mode 100644 templates/emoji_form_error.tmpl diff --git a/handlers/emoji_form.go b/handlers/emoji_form.go index d71d01f..ea2afe0 100644 --- a/handlers/emoji_form.go +++ b/handlers/emoji_form.go @@ -19,7 +19,7 @@ func GetEmojiForm(c *gin.Context) { // 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"}) + c.AbortWithStatus(http.StatusInternalServerError) return } @@ -36,7 +36,7 @@ func PostEmojiForm(c *gin.Context) { // Check if parameters are missing if reactedPostId == "" || reaction == "" { - c.HTML(http.StatusBadRequest, "emoji_form_error.tmpl", gin.H{"errorMessage": "missing parameters"}) + c.AbortWithStatus(http.StatusBadRequest) } // Add the new emoji reaction to the database @@ -44,13 +44,13 @@ func PostEmojiForm(c *gin.Context) { 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_error.tmpl", gin.H{"errorMessage": "error writing to database"}) + c.AbortWithStatus(http.StatusInternalServerError) } // get emoji counts for each emoji emojiCounter, err := GetEmojis(reactedPostId) if err != nil { - c.HTML(http.StatusOK, "emoji_form_error.tmpl", gin.H{"errorMessage": "error getting the emoji counts"}) + c.AbortWithStatus(http.StatusInternalServerError) } // Return the html with the updated emoji counter diff --git a/handlers/emoji_form_test.go b/handlers/emoji_form_test.go index ea80537..d9a95e7 100644 --- a/handlers/emoji_form_test.go +++ b/handlers/emoji_form_test.go @@ -73,7 +73,6 @@ func TestPostEmojiFormMissingParams(t *testing.T) { router.ServeHTTP(w, req) assert.Equal(t, http.StatusBadRequest, w.Code) - assert.Contains(t, w.Body.String(), "missing parameters") } func TestGetEmojis(t *testing.T) { diff --git a/templates/emoji_form.tmpl b/templates/emoji_form.tmpl index a74ce72..0d39924 100644 --- a/templates/emoji_form.tmpl +++ b/templates/emoji_form.tmpl @@ -6,4 +6,4 @@ - +

{{ .errorMessage }}

diff --git a/templates/emoji_form_error.tmpl b/templates/emoji_form_error.tmpl deleted file mode 100644 index d8be0fd..0000000 --- a/templates/emoji_form_error.tmpl +++ /dev/null @@ -1,9 +0,0 @@ -
- - - - - - -
-

{{ .errorMessage }}

From 76279753e3267ffc35e15f2844cb148c4c2cbc3c Mon Sep 17 00:00:00 2001 From: log101 Date: Tue, 25 Jun 2024 15:11:03 +0300 Subject: [PATCH 7/7] chore: add comments --- handlers/comment.go | 3 +++ handlers/emoji_form_test.go | 6 +++--- main.go | 5 ++--- utils/main.go | 2 ++ 4 files changed, 10 insertions(+), 6 deletions(-) diff --git a/handlers/comment.go b/handlers/comment.go index b9e7ccd..d947811 100644 --- a/handlers/comment.go +++ b/handlers/comment.go @@ -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) diff --git a/handlers/emoji_form_test.go b/handlers/emoji_form_test.go index d9a95e7..e596397 100644 --- a/handlers/emoji_form_test.go +++ b/handlers/emoji_form_test.go @@ -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"}) diff --git a/main.go b/main.go index f106334..e439396 100644 --- a/main.go +++ b/main.go @@ -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") diff --git a/utils/main.go b/utils/main.go index 45020c8..97172a7 100644 --- a/utils/main.go +++ b/utils/main.go @@ -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