123 lines
2.5 KiB
Go
123 lines
2.5 KiB
Go
package controllers
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
"strconv"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"example.com/gin/test/models"
|
|
"example.com/gin/test/repositories"
|
|
)
|
|
|
|
type CRUDController interface {
|
|
Create(*gin.Context)
|
|
GetAll(*gin.Context)
|
|
GetById(*gin.Context)
|
|
Update(*gin.Context)
|
|
Delete(*gin.Context)
|
|
}
|
|
|
|
type ShopItemController interface {
|
|
CRUDController
|
|
}
|
|
|
|
type shopItemController struct {}
|
|
|
|
func NewShopItemController() ShopItemController {
|
|
return &shopItemController{}
|
|
}
|
|
|
|
func (rc *shopItemController) GetAll(c *gin.Context) {
|
|
shopItems, err := repositories.ShopItems.GetAll()
|
|
|
|
if err != nil {
|
|
ReplyError(c, fmt.Errorf("Could not query shopItems"))
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, shopItems)
|
|
}
|
|
|
|
func (rc *shopItemController) GetById(c *gin.Context) {
|
|
shopItem, err := repositories.ShopItems.GetById(c.Param("id"))
|
|
|
|
if err != nil {
|
|
ReplyError(c, fmt.Errorf("Could not query shopItem: %v", err))
|
|
return
|
|
}
|
|
|
|
ReplyOK(c, shopItem)
|
|
}
|
|
|
|
func (rc *shopItemController) Create(c *gin.Context) {
|
|
shopItem, err := models.NewShopItem(c)
|
|
|
|
if err != nil {
|
|
ReplyError(c, err)
|
|
}
|
|
|
|
_, err = repositories.ShopItems.Create(shopItem)
|
|
if err != nil {
|
|
ReplyError(c, fmt.Errorf("shopItem creation failed: %s", err))
|
|
return
|
|
}
|
|
|
|
//userID := user.(models.User).ID
|
|
//rc.DB.Model(&models.shopItem{}).Where("id = ?"), room.ID).Association("Admins").Append(&models.User{ID: userID})
|
|
|
|
//if result.Error != nil {
|
|
// ReplyError(c, fmt.Errorf("shopItem creation failed: %s", result.Error))
|
|
// return
|
|
//}
|
|
|
|
ReplyOK(c, "shopItem was created")
|
|
}
|
|
|
|
|
|
func (rc *shopItemController) Update(c *gin.Context) {
|
|
shopItemId, err := strconv.Atoi(c.Param("id"))
|
|
|
|
if err != nil {
|
|
ReplyError(c, fmt.Errorf("shopItem with Id '%s' does not exist", c.Param("id")))
|
|
return
|
|
}
|
|
|
|
shopItem, err := models.NewShopItem(c)
|
|
|
|
if err != nil {
|
|
ReplyError(c, err)
|
|
return
|
|
}
|
|
|
|
shopItem.ID = uint(shopItemId)
|
|
_, err = repositories.ShopItems.Update(shopItem)
|
|
|
|
if err != nil {
|
|
ReplyError(c, fmt.Errorf("shopItem creation failed: %s", err))
|
|
return
|
|
}
|
|
|
|
ReplyOK(c, "shopItem was updated")
|
|
}
|
|
|
|
func (rc *shopItemController) Delete(c *gin.Context) {
|
|
err := repositories.ShopItems.DeleteById(c.Param("id"))
|
|
|
|
if err != nil {
|
|
ReplyError(c, fmt.Errorf("shopItem deletion failed: %s", err))
|
|
return
|
|
}
|
|
|
|
ReplyOK(c, "shopItem was deleted")
|
|
}
|
|
|
|
func ReplyError(ctx *gin.Context, err error) {
|
|
ctx.JSON(http.StatusBadRequest, gin.H{ "error": err.Error() })
|
|
}
|
|
|
|
func ReplyOK(ctx *gin.Context, message any) {
|
|
ctx.JSON(http.StatusOK, message)
|
|
}
|