Добавил создание Товара

This commit is contained in:
Владимир Шалимов 2024-06-06 13:11:07 +05:00
parent 555ab78aaa
commit bd50756728
3 changed files with 39 additions and 15 deletions

View File

@ -2,16 +2,45 @@ package controllers
import (
"github.com/gin-gonic/gin"
"github.com/go-playground/validator/v10"
"golang-test/database"
"golang-test/libs"
"golang-test/message"
"golang-test/validators"
"log"
//"golang-test/migrations"
)
func CreateProduct(product database.Product) gin.H {
//db := migrations.Migrate()
func CreateProduct(c *gin.Context, product database.Product) {
db := database.Connector()
validate := validators.Validate
response := message.Response{Status: 200}
//db.Create(&product)
err := validate.Struct(product)
return gin.H{
"message": "Created",
if err != nil {
response.Error = libs.GetValidationErrors(err.(validator.ValidationErrors))
response.Status = 400
message.SendResponse(c, response)
return
}
err = db.Create(&product).Error
if err != nil {
log.Println(err.Error())
response.Error = gin.H{
"error": err.Error(),
}
response.Status = 500
message.SendResponse(c, response)
return
}
response.Message = gin.H{
"message": "Product created",
}
message.SendResponse(c, response)
}

View File

@ -9,9 +9,9 @@ type Manufacturer struct {
type Product struct {
gorm.Model
Name string
Price uint
ManufacturerID uint
Name string `validate:"required`
Price uint `validate:"required"`
ManufacturerID uint `validate:"required"`
Manufacturer *Manufacturer `gorm:"foreignKey:ManufacturerID;references:ID"`
}

View File

@ -16,16 +16,11 @@ func main() {
r.POST("/product", func(c *gin.Context) {
var product database.Product
err := c.ShouldBind(&product)
if err != nil {
if err := c.ShouldBind(&product); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
//c.JSON(http.StatusOK, &product)
response := controllers.CreateProduct(product)
c.JSON(http.StatusOK, response)
controllers.CreateProduct(c, product)
})
r.POST("/manufacturer", func(c *gin.Context) {