-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
101 lines (73 loc) · 2.07 KB
/
client.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
92
93
94
95
96
97
98
99
100
101
package infra
import (
"context"
"time"
"google.golang.org/api/iterator"
"google.golang.org/api/option"
"cloud.google.com/go/functions/metadata"
"cloud.google.com/go/pubsub"
)
type Client interface {
CreateTopic(ctx context.Context, id string) error
Publish(ctx context.Context, id string, message []byte) error
ListTopics(ctx context.Context) ([]string, error)
}
type client struct {
pubsubClient *pubsub.Client
}
func NewClient(ctx context.Context, projectID string, opts ...option.ClientOption) (Client, error) {
pubsubClient, err := pubsub.NewClient(ctx, projectID, opts...)
if err != nil {
return nil, err
}
return &client{
pubsubClient: pubsubClient,
}, nil
}
var _ Client = &client{}
func (c *client) CreateTopic(ctx context.Context, id string) error {
_, err := c.pubsubClient.CreateTopic(ctx, id)
return err
}
func (c *client) Publish(ctx context.Context, id string, message []byte) error {
_, err := c.pubsubClient.Topic(id).Publish(ctx, &pubsub.Message{
Data: message,
}).Get(ctx)
return err
}
func (c *client) ListTopics(ctx context.Context) ([]string, error) {
it := c.pubsubClient.Topics(ctx)
topics := make([]string, 0, 10)
for {
topic, err := it.Next()
if err == iterator.Done {
break
}
if err != nil {
return nil, err
}
topics = append(topics, topic.ID())
}
return topics, nil
}
type fakeClient struct {
fakeHandler func(ctx context.Context, message *Message) error
topics []string
}
func (c *fakeClient) CreateTopic(ctx context.Context, id string) error {
return nil
}
func (c *fakeClient) Publish(ctx context.Context, id string, message []byte) error {
ctx = metadata.NewContext(ctx, &metadata.Metadata{
EventID: "event-id",
Timestamp: time.Now(),
EventType: "example.com/" + id,
})
return c.fakeHandler(ctx, &Message{Data: message})
}
func (c *fakeClient) ListTopics(ctx context.Context) ([]string, error) {
return c.topics, nil
}
func NewFakeClient(fakeHandler func(ctx context.Context, message *Message) error, topics ...string) Client {
return &fakeClient{fakeHandler: fakeHandler, topics: topics}
}