Commit b864197

mo khan <mo@mokhan.ca>
2025-07-24 16:13:12
chore: start to define an interface for an event aggregator
1 parent 8b7a31f
Changed files (2)
pkg/event/aggregator.go
@@ -0,0 +1,23 @@
+package event
+
+type Event string
+type Subscription func(any)
+
+type Aggregator struct {
+	subscriptions map[Event]Subscription
+}
+
+func New() *Aggregator {
+	return &Aggregator{
+		subscriptions: map[Event]Subscription{},
+	}
+}
+
+func (a *Aggregator) Subscribe(event Event, f Subscription) {
+	a.subscriptions[event] = f
+}
+
+func (a *Aggregator) Publish(event Event, message any) {
+	subscription := a.subscriptions[event]
+	subscription(message)
+}
pkg/event/aggregator_test.go
@@ -0,0 +1,23 @@
+package event
+
+import (
+	"testing"
+
+	"github.com/stretchr/testify/assert"
+)
+
+func TestEventAggregator(t *testing.T) {
+	t.Run("Publish", func(t *testing.T) {
+		events := New()
+		called := false
+
+		events.Subscribe("announcement", func(message any) {
+			called = true
+			assert.Equal(t, "Hello", message)
+		})
+
+		events.Publish("announcement", "Hello")
+
+		assert.True(t, called)
+	})
+}