This repository has been archived by the owner on Nov 8, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 51
/
tranformer.go
71 lines (53 loc) · 1.82 KB
/
tranformer.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 state
import (
"encoding/json"
"github.com/golang/protobuf/proto"
"github.com/s7techlab/cckit/convert"
)
type (
// FromBytesTransformer is used after getState operation for convert value
FromBytesTransformer func(bb []byte, config ...interface{}) (interface{}, error)
// ToBytesTransformer is used before putState operation for convert payload
ToBytesTransformer func(v interface{}, config ...interface{}) ([]byte, error)
// KeyTransformer is used before putState operation for convert key
KeyTransformer func(Key) (Key, error)
// StringTransformer is used before setEvent operation for convert name
StringTransformer func(string) (string, error)
Serializer interface {
ToBytes(interface{}) ([]byte, error)
FromBytes(serialized []byte, target interface{}) (interface{}, error)
}
ProtoSerializer struct {
}
JSONSerializer struct {
}
)
func ConvertFromBytes(bb []byte, config ...interface{}) (interface{}, error) {
// conversion is not needed
if len(config) == 0 {
return bb, nil
}
return convert.FromBytes(bb, config[0])
}
func ConvertToBytes(v interface{}, _ ...interface{}) ([]byte, error) {
return convert.ToBytes(v)
}
// KeyAsIs returns string parts of composite key
func KeyAsIs(key Key) (Key, error) {
return key, nil
}
func NameAsIs(name string) (string, error) {
return name, nil
}
func (ps *ProtoSerializer) ToBytes(entry interface{}) ([]byte, error) {
return proto.Marshal(entry.(proto.Message))
}
func (ps *ProtoSerializer) FromBytes(serialized []byte, target interface{}) (interface{}, error) {
return convert.FromBytes(serialized, target)
}
func (js *JSONSerializer) ToBytes(entry interface{}) ([]byte, error) {
return json.Marshal(entry)
}
func (js *JSONSerializer) FromBytes(serialized []byte, target interface{}) (interface{}, error) {
return convert.JSONUnmarshalPtr(serialized, target)
}