-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_van_test.go
81 lines (64 loc) · 1.55 KB
/
example_van_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package van_test
import (
"context"
"fmt"
"log"
"time"
"github.com/maxpoletaev/van"
)
type InMemoryCounter struct {
value int
}
func (c *InMemoryCounter) Increment() int {
c.value++
return c.value
}
func (c *InMemoryCounter) Value() int {
return c.value
}
type Counter interface {
Value() int
Increment() int
}
// ProvideCounter creates a counter instance
func ProvideCounter() (Counter, error) {
return &InMemoryCounter{}, nil
}
type IncrementCommand struct {
Value uint32
}
// Increment is a handler that processes IncrementCommand
func Increment(ctx context.Context, cmd *IncrementCommand, counter Counter, bus *van.Van) error {
oldValue := counter.Value()
newValue := counter.Increment()
_ = bus.Publish(
CounterUpdatedEvent{
Timestamp: time.Now().Unix(),
OldValue: oldValue,
NewValue: newValue,
},
)
return nil
}
// CounterUpdatedEvent is published whenever the counter is updated
type CounterUpdatedEvent struct {
Timestamp int64
OldValue int
NewValue int
}
// CounterUpdated handles CounterUpdatedEvent
func CounterUpdated(ctx context.Context, evt CounterUpdatedEvent) {
fmt.Printf("counter updated: %d -> %d\n", evt.OldValue, evt.NewValue)
}
func ExampleVan() {
bus := van.New()
bus.ProvideOnce(ProvideCounter)
bus.Handle(IncrementCommand{}, Increment)
bus.Subscribe(CounterUpdatedEvent{}, CounterUpdated)
ctx := context.Background()
if err := bus.Invoke(ctx, &IncrementCommand{}); err != nil {
log.Fatalf("failed to call IncrementCommand: %v", err)
}
// wait for the events to be processed before exit
bus.Wait()
}