flamingo.me/flamingo-commerce/v3@v3.11.0/cart/infrastructure/inMemoryStorage.go (about) 1 package infrastructure 2 3 import ( 4 "context" 5 "errors" 6 "sync" 7 8 "go.opencensus.io/trace" 9 10 domaincart "flamingo.me/flamingo-commerce/v3/cart/domain/cart" 11 ) 12 13 type ( 14 // InMemoryCartStorage - for now the default implementation of GuestCartStorage 15 InMemoryCartStorage struct { 16 guestCarts map[string]*domaincart.Cart 17 locker sync.Locker 18 } 19 ) 20 21 var _ CartStorage = &InMemoryCartStorage{} 22 23 // Inject dependencies and prepare storage 24 // Important: InMemoryStorage MUST be bound AsEagerSingleton, Inject MUST be called in tests to behave as expected 25 func (s *InMemoryCartStorage) Inject() *InMemoryCartStorage { 26 s.locker = &sync.Mutex{} 27 s.guestCarts = make(map[string]*domaincart.Cart) 28 29 return s 30 } 31 32 // HasCart checks if the cart storage has a cart with a given id 33 func (s *InMemoryCartStorage) HasCart(ctx context.Context, id string) bool { 34 _, span := trace.StartSpan(ctx, "cart/InMemoryCartStorage/HasCart") 35 defer span.End() 36 37 s.locker.Lock() 38 defer s.locker.Unlock() 39 40 if _, ok := s.guestCarts[id]; ok { 41 return true 42 } 43 return false 44 } 45 46 // GetCart returns a cart with the given id from the cart storage 47 func (s *InMemoryCartStorage) GetCart(ctx context.Context, id string) (*domaincart.Cart, error) { 48 _, span := trace.StartSpan(ctx, "cart/InMemoryCartStorage/GetCart") 49 defer span.End() 50 51 s.locker.Lock() 52 defer s.locker.Unlock() 53 54 if cart, ok := s.guestCarts[id]; ok { 55 return cart, nil 56 } 57 return nil, errors.New("no cart stored") 58 } 59 60 // StoreCart stores a cart in the storage 61 func (s *InMemoryCartStorage) StoreCart(ctx context.Context, cart *domaincart.Cart) error { 62 _, span := trace.StartSpan(ctx, "cart/InMemoryCartStorage/StoreCart") 63 defer span.End() 64 65 s.locker.Lock() 66 defer s.locker.Unlock() 67 68 s.guestCarts[cart.ID] = cart 69 return nil 70 } 71 72 // RemoveCart from storage 73 func (s *InMemoryCartStorage) RemoveCart(ctx context.Context, cart *domaincart.Cart) error { 74 _, span := trace.StartSpan(ctx, "cart/InMemoryCartStorage/RemoveCart") 75 defer span.End() 76 77 s.locker.Lock() 78 defer s.locker.Unlock() 79 80 delete(s.guestCarts, cart.ID) 81 return nil 82 }