-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathquery.go
More file actions
59 lines (48 loc) · 1.17 KB
/
query.go
File metadata and controls
59 lines (48 loc) · 1.17 KB
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
package bee
import (
"context"
"encoding/json"
"github.com/blinkinglight/bee/gen"
"github.com/blinkinglight/bee/qo"
"github.com/nats-io/nats.go"
"google.golang.org/protobuf/proto"
)
// Querier is a function type that takes a QueryEnvelope and returns a result or an error.
// qo.Subnect - use custom subject instead of default "query.aggregate.get"
// qo.Aggregate - use custom aggregate
func Query(ctx context.Context, fn Querier, opts ...qo.Options) error {
cfg := &qo.Config{
Aggregate: "*",
}
for _, opt := range opts {
opt(cfg)
}
subject := QueryPrefix + "." + cfg.Aggregate + ".get"
if cfg.Subject != "" {
subject = cfg.Subject
}
nc, _ := Nats(ctx)
_, _ = nc.QueueSubscribe(subject, cfg.Aggregate, func(msg *nats.Msg) {
if msg == nil {
return
}
query := &gen.QueryEnvelope{}
if err := proto.Unmarshal(msg.Data, query); err != nil {
msg.Respond([]byte(err.Error()))
return
}
result, err := fn.Query(query)
if err != nil {
msg.Respond([]byte(err.Error()))
return
}
response, err := json.Marshal(result)
if err != nil {
msg.Respond([]byte(err.Error()))
return
}
msg.Respond(response)
})
<-ctx.Done()
return nil
}