Go-TestAPI/controllers/manufacturerController.go

77 lines
2.2 KiB
Go
Raw Normal View History

2024-06-05 08:43:05 +00:00
package controllers
import (
"github.com/gin-gonic/gin"
"github.com/go-playground/validator/v10"
2024-06-05 08:43:05 +00:00
"golang-test/database"
"golang-test/libs"
"golang-test/types"
"golang-test/validators"
2024-06-07 12:52:09 +00:00
"net/http"
2024-06-05 08:43:05 +00:00
)
func CreateManufacturer(c *gin.Context, manufacturer database.Manufacturer) {
db := database.Connector()
validate := validators.Validate
2024-06-05 08:43:05 +00:00
if err := validate.Struct(manufacturer); err != nil {
2024-06-07 12:52:09 +00:00
c.JSON(http.StatusBadRequest, libs.GetValidationErrors(err.(validator.ValidationErrors)))
}
if err := db.Create(&manufacturer).Error; err != nil {
2024-06-07 12:52:09 +00:00
c.JSON(http.StatusBadRequest, types.ErrorResponse{Message: err.Error()})
2024-06-05 08:43:05 +00:00
}
2024-06-07 12:52:09 +00:00
c.JSON(http.StatusCreated, types.MessageResponse{Message: "Manufacturer created successfully"})
2024-06-05 08:43:05 +00:00
}
func DeleteManufacturer(c *gin.Context) {
db := database.Connector()
id := c.Param("id")
var manufacturer database.Manufacturer
if db.First(&manufacturer, id).Error != nil {
2024-06-07 12:52:09 +00:00
c.JSON(http.StatusNotFound, types.NotFoundError("Manufacturer", id))
}
2024-06-07 12:52:09 +00:00
if err := db.Delete(&manufacturer, id).Error; err != nil {
c.JSON(http.StatusBadRequest, types.ErrorResponse{Message: err.Error()})
}
2024-06-07 12:52:09 +00:00
c.JSON(http.StatusOK, types.MessageResponse{Message: "Manufacturer deleted successfully"})
}
func GetManufacturers(c *gin.Context) {
db := database.Connector()
2024-06-07 12:52:09 +00:00
var manufacturers []types.ManufacturerResponse
2024-06-07 12:52:09 +00:00
if err := db.Model(&database.Manufacturer{}).Select("ID", "Name").Scan(&manufacturers).Error; err != nil {
c.JSON(http.StatusBadRequest, types.ErrorResponse{Message: err.Error()})
}
2024-06-07 12:52:09 +00:00
c.JSON(http.StatusOK, manufacturers)
}
func EditManufacture(c *gin.Context, editedManufacturer types.ManufacturerPatchRequest) {
db := database.Connector()
id := c.Param("id")
2024-06-07 12:52:09 +00:00
var manufacturer database.Manufacturer
validate := validators.Validate
2024-06-07 12:52:09 +00:00
if err := validate.Struct(editedManufacturer); err != nil {
c.JSON(http.StatusBadRequest, libs.GetValidationErrors(err.(validator.ValidationErrors)))
}
if db.First(&manufacturer, id).Error != nil {
2024-06-07 12:52:09 +00:00
c.JSON(http.StatusNotFound, types.NotFoundError("Manufacturer", id))
}
db.First(&manufacturer, id)
manufacturer.Name = editedManufacturer.Name
db.Save(&manufacturer)
2024-06-07 12:52:09 +00:00
c.JSON(http.StatusOK, types.MessageResponse{Message: "Manufacturer edited successfully"})
}