Skip to content

Commit

Permalink
Add basic aggregate type
Browse files Browse the repository at this point in the history
  • Loading branch information
theskyinflames-macos authored and theskyinflames-macos committed Dec 20, 2022
1 parent 4701eff commit 95e1903
Show file tree
Hide file tree
Showing 2 changed files with 108 additions and 0 deletions.
62 changes: 62 additions & 0 deletions pkg/ddd/aggregate_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package ddd_test

import (
"sync"
"testing"

"github.com/google/uuid"
"github.com/stretchr/testify/require"
"github.com/theskyinflames/cqrs-eda/pkg/ddd"
)

type TestEvent struct {
name string
}

func (e TestEvent) Name() string {
return e.name
}

func TestRecordEventConcurrent(t *testing.T) {
a := ddd.NewAggregateBasic(uuid.New())

// Record events concurrently
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
for i := 0; i < 1000; i++ {
a.RecordEvent(TestEvent{name: "event1"})
}
}()
go func() {
defer wg.Done()
for i := 0; i < 1000; i++ {
a.RecordEvent(TestEvent{name: "event2"})
}
}()
wg.Wait()

// Check that all events were recorded correctly
events := a.Events()
require.Len(t, events, 2000)

event1Count := 0
event2Count := 0
for _, e := range events {
switch e.Name() {
case "event1":
event1Count++
case "event2":
event2Count++
default:
t.Error("Unexpected event name:", e.Name())
}
}
if event1Count != 1000 {
t.Error("Expected 1000 event1 events, got", event1Count)
}
if event2Count != 1000 {
t.Error("Expected 1000 event2 events, got", event2Count)
}
}
46 changes: 46 additions & 0 deletions pkg/ddd/aggretate.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package ddd

import (
"sync"

"github.com/google/uuid"
)

// Event is self-described
type Event interface {
Name() string
}

// AggregateBasic implements
type AggregateBasic struct {
id uuid.UUID
events []Event

mux *sync.Mutex
}

// NewAggregateBasic is a constructor
func NewAggregateBasic(ID uuid.UUID) AggregateBasic {
return AggregateBasic{id: ID, mux: &sync.Mutex{}}
}

// ID is a getter
func (ab AggregateBasic) ID() uuid.UUID {
return ab.id
}

// RecordEvent is self-described
func (ab *AggregateBasic) RecordEvent(e Event) {
ab.mux.Lock()
defer ab.mux.Unlock()
ab.events = append(ab.events, e)
}

// Events is self-described
func (ab *AggregateBasic) Events() []Event {
ab.mux.Lock()
defer ab.mux.Unlock()
e := ab.events
ab.events = []Event{}
return e
}

0 comments on commit 95e1903

Please sign in to comment.