-
Notifications
You must be signed in to change notification settings - Fork 14
/
array_join.go
108 lines (84 loc) · 2.39 KB
/
array_join.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
102
103
104
105
106
107
108
package transform
import (
"context"
"encoding/json"
"fmt"
"strings"
"github.com/brexhq/substation/config"
iconfig "github.com/brexhq/substation/internal/config"
"github.com/brexhq/substation/internal/errors"
"github.com/brexhq/substation/message"
)
type arrayJoinConfig struct {
// Separator is the string that is used to join data.
Separator string `json:"separator"`
Object iconfig.Object `json:"object"`
}
func (c *arrayJoinConfig) Decode(in interface{}) error {
return iconfig.Decode(in, c)
}
func (c *arrayJoinConfig) Validate() error {
if c.Object.SourceKey == "" && c.Object.TargetKey != "" {
return fmt.Errorf("object_source_key: %v", errors.ErrMissingRequiredOption)
}
if c.Object.SourceKey != "" && c.Object.TargetKey == "" {
return fmt.Errorf("object_target_key: %v", errors.ErrMissingRequiredOption)
}
return nil
}
func newArrayJoin(_ context.Context, cfg config.Config) (*arrayJoin, error) {
conf := arrayJoinConfig{}
if err := conf.Decode(cfg.Settings); err != nil {
return nil, fmt.Errorf("transform: array_join: %v", err)
}
if err := conf.Validate(); err != nil {
return nil, fmt.Errorf("transform: array_join: %v", err)
}
tf := arrayJoin{
conf: conf,
hasObjectKey: conf.Object.SourceKey != "",
hasObjectSetKey: conf.Object.TargetKey != "",
separator: []byte(conf.Separator),
}
return &tf, nil
}
type arrayJoin struct {
conf arrayJoinConfig
hasObjectKey bool
hasObjectSetKey bool
separator []byte
}
func (tf *arrayJoin) Transform(ctx context.Context, msg *message.Message) ([]*message.Message, error) {
if msg.IsControl() {
return []*message.Message{msg}, nil
}
var value message.Value
if tf.hasObjectKey {
value = msg.GetValue(tf.conf.Object.SourceKey)
} else {
value = bytesToValue(msg.Data())
}
if !value.Exists() {
return []*message.Message{msg}, nil
}
if !value.IsArray() {
return []*message.Message{msg}, nil
}
var arr []string
for _, val := range value.Array() {
arr = append(arr, val.String())
}
str := strings.Join(arr, tf.conf.Separator)
if tf.hasObjectSetKey {
if err := msg.SetValue(tf.conf.Object.TargetKey, str); err != nil {
return nil, fmt.Errorf("transform: array_join: %v", err)
}
return []*message.Message{msg}, nil
}
msg.SetData([]byte(str))
return []*message.Message{msg}, nil
}
func (tf *arrayJoin) String() string {
b, _ := json.Marshal(tf.conf)
return string(b)
}