134 lines
2.4 KiB
Go
134 lines
2.4 KiB
Go
package controllers
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
"strconv"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"gorm.io/gorm"
|
|
|
|
"example.com/gin/test/models"
|
|
)
|
|
|
|
type CRUDController interface {
|
|
Create(*gin.Context)
|
|
GetAll(*gin.Context)
|
|
GetById(*gin.Context)
|
|
Update(*gin.Context)
|
|
Delete(*gin.Context)
|
|
}
|
|
|
|
type RoomController interface {
|
|
CRUDController
|
|
}
|
|
|
|
type roomController struct {
|
|
DB *gorm.DB
|
|
}
|
|
|
|
func NewRoomController(db *gorm.DB) RoomController {
|
|
return &roomController{
|
|
DB: db,
|
|
}
|
|
}
|
|
|
|
func (rc *roomController) GetAll(c *gin.Context) {
|
|
var rooms []models.Room
|
|
result := rc.DB.Find(&rooms)
|
|
|
|
if result.Error != nil {
|
|
ReplyError(c, fmt.Errorf("Could not query rooms"))
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, rooms)
|
|
}
|
|
|
|
func (rc *roomController) GetById(c *gin.Context) {
|
|
roomId, err := strconv.Atoi(c.Param("id"))
|
|
|
|
if err != nil {
|
|
ReplyError(c, fmt.Errorf("Room with Id '%s' does not exist", c.Param("id")))
|
|
return
|
|
}
|
|
|
|
var room models.Room
|
|
result := rc.DB.First(&room, uint(roomId))
|
|
|
|
if result.Error != nil {
|
|
ReplyError(c, fmt.Errorf("Could not query room: %v", result.Error))
|
|
return
|
|
}
|
|
|
|
ReplyOK(c, room)
|
|
}
|
|
|
|
func (rc *roomController) Create(c *gin.Context) {
|
|
room, err := models.NewRoom(c)
|
|
|
|
if err != nil {
|
|
ReplyError(c, err)
|
|
}
|
|
|
|
result := rc.DB.Create(&room)
|
|
if result.Error != nil {
|
|
ReplyError(c, fmt.Errorf("Room creation failed: %s", result.Error))
|
|
return
|
|
}
|
|
|
|
ReplyOK(c, "Room was created")
|
|
}
|
|
|
|
|
|
func (rc *roomController) Update(c *gin.Context) {
|
|
roomId, err := strconv.Atoi(c.Param("id"))
|
|
|
|
if err != nil {
|
|
ReplyError(c, fmt.Errorf("Room with Id '%s' does not exist", c.Param("id")))
|
|
return
|
|
}
|
|
|
|
room, err := models.NewRoom(c)
|
|
|
|
if err != nil {
|
|
ReplyError(c, err)
|
|
return
|
|
}
|
|
|
|
room.ID = uint(roomId)
|
|
result := rc.DB.Save(&room)
|
|
if result.Error != nil {
|
|
ReplyError(c, fmt.Errorf("Room creation failed: %s", result.Error))
|
|
return
|
|
}
|
|
|
|
ReplyOK(c, "Room was updated")
|
|
}
|
|
|
|
func (rc *roomController) Delete(c *gin.Context) {
|
|
roomId, err := strconv.Atoi(c.Param("id"))
|
|
|
|
if err != nil {
|
|
ReplyError(c, fmt.Errorf("Room with Id '%s' does not exist", c.Param("id")))
|
|
return
|
|
}
|
|
|
|
result := rc.DB.Delete(&models.Room{}, roomId)
|
|
|
|
if result.Error != nil {
|
|
ReplyError(c, fmt.Errorf("Room deletion failed: %s", result.Error))
|
|
return
|
|
}
|
|
|
|
ReplyOK(c, "Room 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)
|
|
}
|