/
time_to_unix_milli.go
71 lines (57 loc) · 1.52 KB
/
time_to_unix_milli.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
package transform
import (
"context"
"encoding/json"
"fmt"
"time"
"github.com/brexhq/substation/config"
"github.com/brexhq/substation/message"
)
func newTimeToUnixMilli(_ context.Context, cfg config.Config) (*timeToUnixMilli, error) {
conf := timeUnixConfig{}
if err := conf.Decode(cfg.Settings); err != nil {
return nil, fmt.Errorf("transform: time_to_unix_milli: %v", err)
}
if err := conf.Validate(); err != nil {
return nil, fmt.Errorf("transform: time_to_unix_milli: %v", err)
}
tf := timeToUnixMilli{
conf: conf,
isObject: conf.Object.SourceKey != "" && conf.Object.TargetKey != "",
}
return &tf, nil
}
type timeToUnixMilli struct {
conf timeUnixConfig
isObject bool
}
func (tf *timeToUnixMilli) Transform(ctx context.Context, msg *message.Message) ([]*message.Message, error) {
if msg.IsControl() {
return []*message.Message{msg}, nil
}
var value message.Value
if tf.isObject {
value = msg.GetValue(tf.conf.Object.SourceKey)
} else {
value = bytesToValue(msg.Data())
}
if !value.Exists() {
return []*message.Message{msg}, nil
}
// Convert UnixNano to UnixMilli.
date := time.Unix(0, value.Int())
ms := date.UnixMilli()
if tf.isObject {
if err := msg.SetValue(tf.conf.Object.TargetKey, ms); err != nil {
return nil, fmt.Errorf("transform: time_to_unix_milli: %v", err)
}
} else {
value := []byte(fmt.Sprintf("%d", ms))
msg.SetData(value)
}
return []*message.Message{msg}, nil
}
func (tf *timeToUnixMilli) String() string {
b, _ := json.Marshal(tf.conf)
return string(b)
}