Skip to content

Commit 1517966

Browse files
committed
add DeleteProduct method and endpoint for product deletion
1 parent e9f504c commit 1517966

File tree

4 files changed

+53
-0
lines changed

4 files changed

+53
-0
lines changed

cmd/main.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ func main() {
3434
server.POST("/product", ProductController.CreateProduct)
3535
server.GET("/product/:productId", ProductController.GetProductsById)
3636
server.PUT("/product", ProductController.UpdateProduct)
37+
server.DELETE("/product/:productId", ProductController.DeleteProduct)
3738

3839
server.Run(":8000")
3940

controller/product_controller.go

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,3 +100,34 @@ func (p *productController) UpdateProduct(ctx *gin.Context) {
100100

101101
ctx.JSON(http.StatusOK, product)
102102
}
103+
104+
func (p *productController) DeleteProduct(ctx *gin.Context) {
105+
id := ctx.Param("productId")
106+
if id == "" {
107+
response := model.Response{
108+
Message: "Product ID cannot be null",
109+
}
110+
ctx.JSON(http.StatusBadRequest, response)
111+
return
112+
}
113+
114+
productId, err := strconv.Atoi(id)
115+
if err != nil {
116+
response := model.Response{
117+
Message: "Product Id need to be number",
118+
}
119+
ctx.JSON(http.StatusBadRequest, response)
120+
return
121+
}
122+
123+
err = p.productUseCase.DeleteProduct(productId)
124+
if err != nil {
125+
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
126+
return
127+
}
128+
129+
response := model.Response{
130+
Message: "Product deleted successfully",
131+
}
132+
ctx.JSON(http.StatusOK, response)
133+
}

repository/product_repository.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,3 +111,20 @@ func (pr *ProductRepository) UpdateProduct(product model.Product) error {
111111

112112
return nil
113113
}
114+
115+
func (pr *ProductRepository) DeleteProduct(id int) error {
116+
query, err := pr.connection.Prepare("DELETE FROM product WHERE id = $1")
117+
if err != nil {
118+
fmt.Println(err)
119+
return err
120+
}
121+
defer query.Close()
122+
123+
_, err = query.Exec(id)
124+
if err != nil {
125+
fmt.Println(err)
126+
return err
127+
}
128+
129+
return nil
130+
}

usecase/product_usecase.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,3 +39,7 @@ func (pu *ProductUseCase) GetProductById(id_product int) (*model.Product, error)
3939
func (pu *ProductUseCase) UpdateProduct(product model.Product) error {
4040
return pu.repository.UpdateProduct(product)
4141
}
42+
43+
func (pu *ProductUseCase) DeleteProduct(id int) error {
44+
return pu.repository.DeleteProduct(id)
45+
}

0 commit comments

Comments
 (0)