/
handler.go
91 lines (72 loc) · 2.51 KB
/
handler.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
82
83
84
85
86
87
88
89
90
91
package handler
import (
"context"
"fmt"
"github.com/segmentio/kafka-go"
"google.golang.org/protobuf/proto"
"github.com/ezotrank/playground/saga-choreography/bank/internal/repository"
pbwallet "github.com/ezotrank/playground/saga-choreography/wallet/proto/gen/go/wallet/v1"
)
type IRepository interface {
SaveAccount(ctx context.Context, account *repository.Account) error
SaveTransaction(ctx context.Context, transaction *repository.Transaction) error
}
type IProducer interface {
NewAccountEvent(ctx context.Context, account *repository.Account) error
NewTransactionEvent(ctx context.Context, transaction *repository.Transaction) error
}
type IExternalServiceClient interface {
CreateAccount(ctx context.Context, account *repository.Account) error
}
func NewHandler(repo IRepository, producer IProducer, external IExternalServiceClient) *Handler {
return &Handler{
repo: repo,
producer: producer,
external: external,
}
}
type Handler struct {
repo IRepository
external IExternalServiceClient
producer IProducer
}
func (h *Handler) WalletUsersHandler(ctx context.Context, msg kafka.Message) error {
var user pbwallet.User
if err := proto.Unmarshal(msg.Value, &user); err != nil {
return fmt.Errorf("failed to unmarshal wallet user: %v", err)
}
account := &repository.Account{
AccountID: user.UserId,
UserID: user.UserId,
Status: repository.AccountStatusRegistered,
}
if err := h.external.CreateAccount(ctx, account); err != nil {
return fmt.Errorf("failed to create account: %v", err)
}
if err := h.repo.SaveAccount(ctx, account); err != nil {
return fmt.Errorf("failed to save account: %v", err)
}
if err := h.producer.NewAccountEvent(ctx, account); err != nil {
return fmt.Errorf("failed to send account event: %v", err)
}
return nil
}
func (h *Handler) WalletTransactionsHandler(ctx context.Context, msg kafka.Message) error {
var pbtrx pbwallet.Transaction
if err := proto.Unmarshal(msg.Value, &pbtrx); err != nil {
return fmt.Errorf("failed to unmarshal wallet transaction: %v", err)
}
trx := &repository.Transaction{
TransactionID: pbtrx.TransactionId,
AccountID: pbtrx.UserId, // TODO(ezo): change to account id
Amount: int(pbtrx.Amount),
}
trx.Status = repository.TransactionStatusSucceed
if err := h.repo.SaveTransaction(ctx, trx); err != nil {
return fmt.Errorf("failed to save transaction: %v", err)
}
if err := h.producer.NewTransactionEvent(ctx, trx); err != nil {
return fmt.Errorf("failed to send transaction event: %v", err)
}
return nil
}