/
commands.go
78 lines (64 loc) · 2.38 KB
/
commands.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
package handlers
import (
"context"
"time"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
"github.com/LordMoMA/Intelli-Mall/internal/am"
"github.com/LordMoMA/Intelli-Mall/internal/ddd"
"github.com/LordMoMA/Intelli-Mall/internal/errorsotel"
"github.com/LordMoMA/Intelli-Mall/internal/registry"
"github.com/LordMoMA/Intelli-Mall/ordering/internal/application"
"github.com/LordMoMA/Intelli-Mall/ordering/internal/application/commands"
"github.com/LordMoMA/Intelli-Mall/ordering/orderingpb"
)
type commandHandlers struct {
app application.App
}
func NewCommandHandlers(reg registry.Registry, app application.App, replyPublisher am.ReplyPublisher, mws ...am.MessageHandlerMiddleware) am.MessageHandler {
return am.NewCommandHandler(reg, replyPublisher, commandHandlers{
app: app,
}, mws...)
}
func RegisterCommandHandlers(subscriber am.MessageSubscriber, handlers am.MessageHandler) error {
_, err := subscriber.Subscribe(orderingpb.CommandChannel, handlers, am.MessageFilter{
orderingpb.RejectOrderCommand,
orderingpb.ApproveOrderCommand,
}, am.GroupName("ordering-commands"))
return err
}
func (h commandHandlers) HandleCommand(ctx context.Context, cmd ddd.Command) (reply ddd.Reply, err error) {
span := trace.SpanFromContext(ctx)
defer func(started time.Time) {
if err != nil {
span.AddEvent(
"Encountered an error handling command",
trace.WithAttributes(errorsotel.ErrAttrs(err)...),
)
}
span.AddEvent("Handled command", trace.WithAttributes(
attribute.Int64("TookMS", time.Since(started).Milliseconds()),
))
}(time.Now())
span.AddEvent("Handling command", trace.WithAttributes(
attribute.String("Command", cmd.CommandName()),
))
switch cmd.CommandName() {
case orderingpb.RejectOrderCommand:
return h.doRejectOrder(ctx, cmd)
case orderingpb.ApproveOrderCommand:
return h.doApproveOrder(ctx, cmd)
}
return nil, nil
}
func (h commandHandlers) doRejectOrder(ctx context.Context, cmd ddd.Command) (ddd.Reply, error) {
payload := cmd.Payload().(*orderingpb.RejectOrder)
return nil, h.app.RejectOrder(ctx, commands.RejectOrder{ID: payload.GetId()})
}
func (h commandHandlers) doApproveOrder(ctx context.Context, cmd ddd.Command) (ddd.Reply, error) {
payload := cmd.Payload().(*orderingpb.ApproveOrder)
return nil, h.app.ApproveOrder(ctx, commands.ApproveOrder{
ID: payload.GetId(),
ShoppingID: payload.GetShoppingId(),
})
}