114 lines
2.1 KiB
Go
114 lines
2.1 KiB
Go
package handlers
|
|
|
|
import (
|
|
database "app/database"
|
|
"app/models"
|
|
"app/repositories"
|
|
"net/http"
|
|
"strconv"
|
|
|
|
"github.com/labstack/echo/v4"
|
|
)
|
|
|
|
// Create(c *models.Comment) error
|
|
// GetUserComments(id uint) ([]models.Comment, error)
|
|
// GetProductComments(id uint) ([]models.Comment, error)
|
|
// UpdateContent(id uint, content string) error
|
|
// Delete(id uint) error
|
|
|
|
func initComment() *repositories.Comment_repository {
|
|
db := database.Db()
|
|
commentRepository := new(repositories.Comment_repository)
|
|
commentRepository.DB = &db
|
|
|
|
return commentRepository
|
|
}
|
|
|
|
func CreateComment(c echo.Context) error {
|
|
comment := new(models.Comment)
|
|
|
|
if err := c.Bind(comment); err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
commentRepository := initComment()
|
|
|
|
err := commentRepository.Create(comment)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
return c.JSON(http.StatusCreated, comment)
|
|
|
|
}
|
|
|
|
func GetUserComments(c echo.Context) error {
|
|
id, err := strconv.Atoi(c.Param("id"))
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
commentRepository := initComment()
|
|
|
|
comments, err := commentRepository.GetUserComments(uint(id))
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
return c.JSON(http.StatusAccepted, comments)
|
|
}
|
|
|
|
func GetProductComments(c echo.Context) error {
|
|
id, err := strconv.Atoi(c.Param("id"))
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
commentRepository := initComment()
|
|
|
|
comments, err := commentRepository.GetUserComments(uint(id))
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
return c.JSON(http.StatusAccepted, comments)
|
|
}
|
|
|
|
func UpdateComment(c echo.Context) error {
|
|
id, err := strconv.Atoi(c.Param("id"))
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
var update struct {
|
|
NewContent string `json:"content"`
|
|
}
|
|
|
|
commentRepository := initComment()
|
|
|
|
if update.NewContent != "" {
|
|
err = commentRepository.UpdateContent(uint(id), update.NewContent)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
}
|
|
|
|
return c.String(http.StatusAccepted, "updated")
|
|
}
|
|
|
|
func DeleteComment(c echo.Context) error {
|
|
id, err := strconv.Atoi(c.Param("id"))
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
commentRepository := initComment()
|
|
|
|
err = commentRepository.Delete(uint(id))
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
return c.String(http.StatusAccepted, "removed")
|
|
}
|