Skip to content

Commit

Permalink
fix: cart modules store and json annotations (#516)
Browse files Browse the repository at this point in the history
  • Loading branch information
wesbillman authored Oct 20, 2023
1 parent 9ef0ca0 commit 2ff420a
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 18 deletions.
18 changes: 9 additions & 9 deletions examples/online-boutique/services/cart/cart.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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{}
Expand Down
26 changes: 17 additions & 9 deletions examples/online-boutique/services/cart/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

Expand Down

0 comments on commit 2ff420a

Please sign in to comment.