Skip to content

Commit

Permalink
Add DELETE endpoint to remove items from cart
Browse files Browse the repository at this point in the history
Implemented a new DELETE endpoint to handle item removal from the user's cart. Added the corresponding handler and service logic to process the deletion, including interactions with the database to ensure item removal. Updated the cart service interface to include the delete functionality.
  • Loading branch information
mukulmantosh committed Sep 4, 2024
1 parent 3c88e2b commit b5193af
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 0 deletions.
1 change: 1 addition & 0 deletions pkg/abstract/cart/cart.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,5 @@ type Cart interface {

type CartItems interface {
ListItems(ctx context.Context, cartId int64) (*[]cart.CartItems, error)
DeleteItem(ctx context.Context, cartItemId int64) (bool, error)
}
18 changes: 18 additions & 0 deletions pkg/handler/cart/cart.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"context"
"github.com/gin-gonic/gin"
"net/http"
"strconv"
"time"
)

Expand Down Expand Up @@ -78,3 +79,20 @@ func (s *CartHandler) getItems(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"items": items})
return
}

func (s *CartHandler) deleteItemFromCart(c *gin.Context) {
ctx, cancel := context.WithTimeout(c.Request.Context(), 5*time.Second)
defer cancel()

cartItemId := c.Param("id")
cartItemID, _ := strconv.ParseInt(cartItemId, 10, 64)

_, err := s.service.DeleteItem(ctx, cartItemID)
if err != nil {
c.AbortWithStatusJSON(http.StatusNotFound, gin.H{"error": err.Error()})
return
}

c.Status(http.StatusNoContent)

}
2 changes: 2 additions & 0 deletions pkg/handler/cart/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,7 @@ func (s *CartHandler) registerGroup(middleware ...gin.HandlerFunc) gin.IRoutes {
func (s *CartHandler) routes() http.Handler {
s.router.POST("/add", s.addToCart)
s.router.GET("/list", s.getItems)
s.router.DELETE("/remove/:id", s.deleteItemFromCart)

return s.serve.Gin
}
16 changes: 16 additions & 0 deletions pkg/service/cart/delete_item_from_cart.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package cart

import (
"Go_Food_Delivery/pkg/database"
"context"
)

func (cartSrv *CartService) DeleteItem(ctx context.Context, cartItemId int64) (bool, error) {
filter := database.Filter{"cart_item_id": cartItemId}

_, err := cartSrv.db.Delete(ctx, "cart_items", filter)
if err != nil {
return false, err
}
return true, nil
}

0 comments on commit b5193af

Please sign in to comment.