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) {