Skip to content

Instantly share code, notes, and snippets.

@percybolmer
Last active August 29, 2021 06:30
Show Gist options
  • Save percybolmer/85ae51dc8d58d46b4f39117a166f782c to your computer and use it in GitHub Desktop.
Save percybolmer/85ae51dc8d58d46b4f39117a166f782c to your computer and use it in GitHub Desktop.
// Package memory is a in-memory implementation of the customer repository
package memory
import (
"fmt"
"sync"
"github.com/google/uuid"
"github.com/percybolmer/ddd-go/aggregate"
"github.com/percybolmer/ddd-go/domain/customer"
)
// MemoryRepository fulfills the CustomerRepository interface
type MemoryRepository struct {
customers map[uuid.UUID]aggregate.Customer
sync.Mutex
}
// New is a factory function to generate a new repository of customers
func New() *MemoryRepository {
return &MemoryRepository{
customers: make(map[uuid.UUID]aggregate.Customer),
}
}
// Get finds a customer by ID
func (mr *MemoryRepository) Get(id uuid.UUID) (aggregate.Customer, error) {
if customer, ok := mr.customers[id]; ok {
return customer, nil
}
return aggregate.Customer{}, customer.ErrCustomerNotFound
}
// Add will add a new customer to the repository
func (mr *MemoryRepository) Add(c aggregate.Customer) error {
if mr.customers == nil {
// Saftey check if customers is not create, shouldn't happen if using the Factory, but you never know
mr.Lock()
mr.customers = make(map[uuid.UUID]aggregate.Customer)
mr.Unlock()
}
// Make sure Customer isn't already in the repository
if _, ok := mr.customers[c.GetID()]; ok {
return fmt.Errorf("customer already exists: %w", customer.ErrFailedToAddCustomer)
}
mr.Lock()
mr.customers[c.GetID()] = c
mr.Unlock()
return nil
}
// Update will replace an existing customer information with the new customer information
func (mr *MemoryRepository) Update(c aggregate.Customer) error {
// Make sure Customer is in the repository
if _, ok := mr.customers[c.GetID()]; !ok {
return fmt.Errorf("customer does not exist: %w", customer.ErrUpdateCustomer)
}
mr.Lock()
mr.customers[c.GetID()] = c
mr.Unlock()
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment