ai pubsub
This commit is contained in:
@@ -3,9 +3,11 @@ package cart
|
||||
import (
|
||||
"encoding/json"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.tornberg.me/go-cart-actor/pkg/actor"
|
||||
messages "git.tornberg.me/go-cart-actor/pkg/messages"
|
||||
"git.tornberg.me/go-cart-actor/pkg/voucher"
|
||||
)
|
||||
@@ -184,6 +186,40 @@ func (c *CartGrain) GetCurrentState() (*CartGrain, error) {
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// Notify handles incoming events, e.g., inventory changes.
|
||||
func (c *CartGrain) Notify(event actor.Event) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
// Example: if event is inventory change for a SKU in the cart
|
||||
if strings.HasPrefix(event.Topic, "inventory:") {
|
||||
sku := strings.TrimPrefix(event.Topic, "inventory:")
|
||||
for _, item := range c.Items {
|
||||
if item.Sku == sku {
|
||||
// Update stock status based on payload, e.g., if payload is bool available
|
||||
if available, ok := event.Payload.(bool); ok {
|
||||
if available {
|
||||
item.Stock = StockStatus(1) // assuming 1 is in stock
|
||||
} else {
|
||||
item.Stock = StockStatus(0) // out of stock
|
||||
}
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *CartGrain) UpdateSubscriptions(pubsub *actor.PubSub) {
|
||||
pubsub.UnsubscribeAll(c.GetId())
|
||||
skuSet := make(map[string]bool)
|
||||
for _, item := range c.Items {
|
||||
skuSet[item.Sku] = true
|
||||
}
|
||||
for sku := range skuSet {
|
||||
pubsub.Subscribe("inventory:"+sku, c.GetId())
|
||||
}
|
||||
}
|
||||
|
||||
func (c *CartGrain) GetState() ([]byte, error) {
|
||||
return json.Marshal(c)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user