126 lines
2.6 KiB
Go
126 lines
2.6 KiB
Go
package controllers
|
|
|
|
import (
|
|
"strconv"
|
|
|
|
"github.com/dungnt11/todoms_golang/internal/services"
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// ProductController triển khai IProductController
|
|
type ProductController struct {
|
|
productService services.IProductService
|
|
}
|
|
|
|
// NewProductController tạo một instance mới của ProductController
|
|
func NewProductController(productService services.IProductService) *ProductController {
|
|
return &ProductController{
|
|
productService: productService,
|
|
}
|
|
}
|
|
|
|
// CreateProduct xử lý tạo sản phẩm mới
|
|
func (pc *ProductController) CreateProduct(c *gin.Context) {
|
|
// Gọi service để thực hiện logic tạo sản phẩm
|
|
result, err := pc.productService.CreateProduct(c)
|
|
|
|
if err != nil {
|
|
c.JSON(400, gin.H{
|
|
"error": err.Error(),
|
|
})
|
|
return
|
|
}
|
|
|
|
c.JSON(201, result)
|
|
}
|
|
|
|
// GetProduct xử lý lấy thông tin sản phẩm theo ID
|
|
func (pc *ProductController) GetProduct(c *gin.Context) {
|
|
// Lấy ID từ param
|
|
idStr := c.Param("id")
|
|
id, err := strconv.ParseUint(idStr, 10, 32)
|
|
if err != nil {
|
|
c.JSON(400, gin.H{
|
|
"error": "ID không hợp lệ",
|
|
})
|
|
return
|
|
}
|
|
|
|
// Gọi service để lấy thông tin sản phẩm
|
|
result, err := pc.productService.GetProduct(uint(id))
|
|
|
|
if err != nil {
|
|
c.JSON(404, gin.H{
|
|
"error": err.Error(),
|
|
})
|
|
return
|
|
}
|
|
|
|
c.JSON(200, result)
|
|
}
|
|
|
|
// GetAllProducts xử lý lấy tất cả sản phẩm
|
|
func (pc *ProductController) GetAllProducts(c *gin.Context) {
|
|
// Gọi service để lấy tất cả sản phẩm
|
|
result, err := pc.productService.GetAllProducts()
|
|
|
|
if err != nil {
|
|
c.JSON(400, gin.H{
|
|
"error": err.Error(),
|
|
})
|
|
return
|
|
}
|
|
|
|
c.JSON(200, result)
|
|
}
|
|
|
|
// UpdateProduct xử lý cập nhật thông tin sản phẩm
|
|
func (pc *ProductController) UpdateProduct(c *gin.Context) {
|
|
// Lấy ID từ param
|
|
idStr := c.Param("id")
|
|
id, err := strconv.ParseUint(idStr, 10, 32)
|
|
if err != nil {
|
|
c.JSON(400, gin.H{
|
|
"error": "ID không hợp lệ",
|
|
})
|
|
return
|
|
}
|
|
|
|
// Gọi service để cập nhật thông tin sản phẩm
|
|
result, err := pc.productService.UpdateProduct(uint(id), c)
|
|
|
|
if err != nil {
|
|
c.JSON(400, gin.H{
|
|
"error": err.Error(),
|
|
})
|
|
return
|
|
}
|
|
|
|
c.JSON(200, result)
|
|
}
|
|
|
|
// DeleteProduct xử lý xóa sản phẩm
|
|
func (pc *ProductController) DeleteProduct(c *gin.Context) {
|
|
// Lấy ID từ param
|
|
idStr := c.Param("id")
|
|
id, err := strconv.ParseUint(idStr, 10, 32)
|
|
if err != nil {
|
|
c.JSON(400, gin.H{
|
|
"error": "ID không hợp lệ",
|
|
})
|
|
return
|
|
}
|
|
|
|
// Gọi service để xóa sản phẩm
|
|
result, err := pc.productService.DeleteProduct(uint(id))
|
|
|
|
if err != nil {
|
|
c.JSON(400, gin.H{
|
|
"error": err.Error(),
|
|
})
|
|
return
|
|
}
|
|
|
|
c.JSON(200, result)
|
|
}
|