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" "strconv" //"golang-test/migrations" ) func CreateProduct(c *gin.Context, product database.Product) { db := database.Connector() validate := validators.Validate response := message.Response{Status: 200} err := validate.Struct(product) if err != nil { response.Error = libs.GetValidationErrors(err.(validator.ValidationErrors)) response.Status = 400 message.SendResponse(c, response) return } if err := db.First(&database.Manufacturer{}, product.ManufacturerID).Error; err != nil { response.Error = gin.H{ "error": "Manufacturer with id '" + strconv.Itoa(int(product.ManufacturerID)) + "' not found", } } 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) } func DeleteProduct(c *gin.Context) { db := database.Connector() response := message.Response{Status: 200} id := c.Param("id") var product database.Product if db.First(&product, id).Error != nil { response.Error = gin.H{ "error": "Product with id '" + id + "' not found", } response.Status = 404 message.SendResponse(c, response) return } db.Delete(&product, id) response.Message = gin.H{ "message": "Product deleted", } message.SendResponse(c, response) } //func GetProducts(c *gin.Context) { // // db := database.Connector() // response := message.Response{Status: 200} // var product []database.Product // // resp := []interface{}{} // // db.Find(&product) // // for _, productItem := range product { // resp = append(resp, gin.H{ // "id": productItem.ID, // "name": productItem.Name, // "price": productItem.Price, // "manufacturer_ID": productItem.Manufacturer.ID, // "manufacturer_Name": productItem.Manufacturer.Name, // }) // log.Println(productItem.Manufacturer.Name) // } // // response.Message = gin.H{ // "products": resp, // } // // message.SendResponse(c, response) //} func GetProductInfo(c *gin.Context) { db := database.Connector() response := message.Response{Status: 200} id := c.Param("id") var product database.Product if err := db.First(&product, id).Error; err != nil { response.Error = gin.H{ "error": "Product with id '" + id + "' not found", } response.Status = 404 message.SendResponse(c, response) return } response.Message = gin.H{ "product": gin.H{ "id": product.ID, "name": product.Name, "price": product.Price, "manufacturer_ID": product.ManufacturerID, "manufacturer_Name": product.Manufacturer.Name, }, } }