diff --git a/examples/online-boutique/services/cart/cart.go b/examples/online-boutique/services/cart/cart.go index f13675a017..f73cd9aada 100644 --- a/examples/online-boutique/services/cart/cart.go +++ b/examples/online-boutique/services/cart/cart.go @@ -8,20 +8,20 @@ import ( var store = NewStore() type Item struct { - ProductID string - Quantity int + ProductID string `json:"productID"` + Quantity int `json:"quantity"` } type AddItemRequest struct { - UserID string - Item Item + UserID string `json:"userID"` + Item Item `json:"item"` } type AddItemResponse struct{} type Cart struct { - UserID string - Items []Item + UserID string `json:"userID"` + Items []Item `json:"items"` } //ftl:verb @@ -32,17 +32,17 @@ func AddItem(ctx context.Context, req AddItemRequest) (AddItemResponse, error) { } type GetCartRequest struct { - UserID string + UserID string `json:"userID"` } //ftl:verb //ftl:ingress GET /cart func GetCart(ctx context.Context, req GetCartRequest) (Cart, error) { - return Cart{Items: store.Get(req.UserID)}, nil + return Cart{Items: store.Get(req.UserID), UserID: req.UserID}, nil } type EmptyCartRequest struct { - UserID string + UserID string `json:"userID"` } type EmptyCartResponse struct{} diff --git a/examples/online-boutique/services/cart/store.go b/examples/online-boutique/services/cart/store.go index 9f36658bab..536ec527c0 100644 --- a/examples/online-boutique/services/cart/store.go +++ b/examples/online-boutique/services/cart/store.go @@ -19,20 +19,28 @@ func NewStore() *Store { return &Store{carts: cache} } -func (s *Store) Add(userID string, item Item) { +func (s *Store) Add(userID string, newItem Item) { s.lock.Lock() defer s.lock.Unlock() items, ok := s.carts.Get(userID) - if ok { - for i, item := range items { - if item.ProductID == item.ProductID { - items[i].Quantity += item.Quantity - break - } + if !ok { + s.carts.Add(userID, []Item{newItem}) + return + } + + found := false + for i, existingItem := range items { + if existingItem.ProductID == newItem.ProductID { + items[i].Quantity += newItem.Quantity + found = true + break } - } else { - items = []Item{item} } + + if !found { + items = append(items, newItem) + } + s.carts.Add(userID, items) }