-
Notifications
You must be signed in to change notification settings - Fork 72
/
json.go
63 lines (55 loc) · 1.54 KB
/
json.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
package kafka
import (
"encoding/json"
)
type JSONSerde struct {
Serdes
}
// Serialize serializes a JSON object as map to bytes.
func (*JSONSerde) Serialize(data interface{}, schema *Schema) ([]byte, *Xk6KafkaError) {
var jsonObject []byte
if data, ok := data.(map[string]interface{}); ok {
if encodedData, err := json.Marshal(data); err == nil {
jsonObject = encodedData
} else {
return nil, ErrInvalidDataType
}
} else {
return nil, ErrInvalidDataType
}
if schema != nil {
// Validate the JSON object against the schema only if the schema is
// provided.
jsonSchema := schema.JsonSchema()
if jsonSchema != nil {
if err := jsonSchema.Validate(data); err != nil {
return nil, NewXk6KafkaError(failedValidateJSON,
"Failed to validate JSON against schema",
err)
}
} else {
return nil, ErrInvalidSchema
}
}
return jsonObject, nil
}
// Deserialize deserializes a map from bytes to be exported as object to JS.
func (*JSONSerde) Deserialize(data []byte, schema *Schema) (interface{}, *Xk6KafkaError) {
var jsonObject interface{}
if err := json.Unmarshal(data, &jsonObject); err != nil {
return nil, NewXk6KafkaError(failedUnmarshalJSON,
"Failed to unmarshal JSON data",
err)
}
if schema != nil {
// Validate the JSON object against the schema only if the schema is
// provided.
if err := schema.JsonSchema().Validate(jsonObject); err != nil {
err := NewXk6KafkaError(failedDecodeJSONFromBinary,
"Failed to decode data from JSON",
err)
return nil, err
}
}
return jsonObject, nil
}