-
Notifications
You must be signed in to change notification settings - Fork 13
/
transformer.go
191 lines (167 loc) · 4.81 KB
/
transformer.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package json
import (
"encoding/json"
"strings"
"github.com/MainfluxLabs/mainflux/pkg/errors"
"github.com/MainfluxLabs/mainflux/pkg/messaging"
"github.com/MainfluxLabs/mainflux/pkg/transformers"
)
const sep = "/"
var (
keys = [...]string{"publisher", "protocol", "channel", "subtopic"}
// ErrTransform represents an error during parsing message.
ErrTransform = errors.New("unable to parse JSON object")
// ErrInvalidKey represents the use of a reserved message field.
ErrInvalidKey = errors.New("invalid object key")
// ErrInvalidTimeField represents the use an invalid time field.
ErrInvalidTimeField = errors.New("invalid time field")
errUnknownFormat = errors.New("unknown format of JSON message")
errInvalidFormat = errors.New("invalid JSON object")
errInvalidNestedJSON = errors.New("invalid nested JSON object")
)
// TimeField represents the message fields to use as timestamp
type TimeField struct {
Name string `json:"name"`
Format string `json:"format"`
Location string `json:"location"`
}
type transformerService struct {
timeFields []TimeField
}
// New returns a new JSON transformer.
func New() transformers.Transformer {
return &transformerService{}
}
// Transform transforms Mainflux message to a list of JSON messages.
func (ts *transformerService) Transform(msg messaging.Message) (interface{}, error) {
ret := Message{
Publisher: msg.Publisher,
Created: msg.Created,
Protocol: msg.Protocol,
Channel: msg.Channel,
}
subs := strings.Split(msg.Subtopic, ".")
switch {
case msg.Subtopic == "":
return nil, errors.Wrap(ErrTransform, errUnknownFormat)
case len(subs) == 1:
ret.Subtopic = ""
default:
ret.Subtopic = strings.Join(subs[:len(subs)-1], ".")
}
format := subs[len(subs)-1]
var payload interface{}
if err := json.Unmarshal(msg.Payload, &payload); err != nil {
return nil, errors.Wrap(ErrTransform, err)
}
switch p := payload.(type) {
case map[string]interface{}:
ret.Payload = p
// Apply timestamp transformation rules depending on key/unit pairs
ts, err := ts.transformTimeField(p, *msg.Profile.Transformer)
if err != nil {
return nil, errors.Wrap(ErrInvalidTimeField, err)
}
if ts != 0 {
ret.Created = ts
}
return Messages{[]Message{ret}, format}, nil
case []interface{}:
res := []Message{}
// Make an array of messages from the root array.
for _, val := range p {
v, ok := val.(map[string]interface{})
if !ok {
return nil, errors.Wrap(ErrTransform, errInvalidNestedJSON)
}
newMsg := ret
// Apply timestamp transformation rules depending on key/unit pairs
ts, err := ts.transformTimeField(v, *msg.Profile.Transformer)
if err != nil {
return nil, errors.Wrap(ErrInvalidTimeField, err)
}
if ts != 0 {
ret.Created = ts
}
newMsg.Payload = v
res = append(res, newMsg)
}
return Messages{res, format}, nil
default:
return nil, errors.Wrap(ErrTransform, errInvalidFormat)
}
}
// ParseFlat receives flat map that represents complex JSON objects and returns
// the corresponding complex JSON object with nested maps. It's the opposite
// of the Flatten function.
func ParseFlat(flat interface{}) interface{} {
msg := make(map[string]interface{})
switch v := flat.(type) {
case map[string]interface{}:
for key, value := range v {
if value == nil {
continue
}
subKeys := strings.Split(key, sep)
n := len(subKeys)
if n == 1 {
msg[key] = value
continue
}
current := msg
for i, k := range subKeys {
if _, ok := current[k]; !ok {
current[k] = make(map[string]interface{})
}
if i == n-1 {
current[k] = value
break
}
current = current[k].(map[string]interface{})
}
}
}
return msg
}
// Flatten makes nested maps flat using composite keys created by concatenation of the nested keys.
func Flatten(m map[string]interface{}) (map[string]interface{}, error) {
return flatten("", make(map[string]interface{}), m)
}
func flatten(prefix string, m, m1 map[string]interface{}) (map[string]interface{}, error) {
for k, v := range m1 {
if strings.Contains(k, sep) {
return nil, ErrInvalidKey
}
for _, key := range keys {
if k == key {
return nil, ErrInvalidKey
}
}
switch val := v.(type) {
case map[string]interface{}:
var err error
m, err = flatten(prefix+k+sep, m, val)
if err != nil {
return nil, err
}
default:
m[prefix+k] = v
}
}
return m, nil
}
func (ts *transformerService) transformTimeField(payload map[string]interface{}, transformer messaging.Transformer) (int64, error) {
if transformer.TimeField == "" {
return 0, nil
}
if val, ok := payload[transformer.TimeField]; ok {
t, err := parseTimestamp(transformer.TimeFormat, val, transformer.TimeLocation)
if err != nil {
return 0, err
}
return t.UnixNano(), nil
}
return 0, nil
}