From bd50756728a36f151a812022900e2825d5a59d96 Mon Sep 17 00:00:00 2001 From: ravonzz Date: Thu, 6 Jun 2024 13:11:07 +0500 Subject: [PATCH] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8=D0=BB=20?= =?UTF-8?q?=D1=81=D0=BE=D0=B7=D0=B4=D0=B0=D0=BD=D0=B8=D0=B5=20=D0=A2=D0=BE?= =?UTF-8?q?=D0=B2=D0=B0=D1=80=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- controllers/productController.go | 39 ++++++++++++++++++++++++++++---- database/models.go | 6 ++--- main.go | 9 ++------ 3 files changed, 39 insertions(+), 15 deletions(-) diff --git a/controllers/productController.go b/controllers/productController.go index 8a53e85..dbe25df 100644 --- a/controllers/productController.go +++ b/controllers/productController.go @@ -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) } diff --git a/database/models.go b/database/models.go index 0e94c6f..be1fb12 100644 --- a/database/models.go +++ b/database/models.go @@ -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"` } diff --git a/main.go b/main.go index da5da86..f83272d 100644 --- a/main.go +++ b/main.go @@ -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) {