-
Notifications
You must be signed in to change notification settings - Fork 23
/
selfDescribing.go
75 lines (63 loc) · 1.66 KB
/
selfDescribing.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
// Copyright (c) 2022 Silverton Data, Inc.
// You may use, distribute, and modify this code under the terms of the Apache-2.0 license, a copy of
// which may be found at https://github.com/silverton-io/buz/blob/main/LICENSE
package envelope
import (
"database/sql/driver"
"encoding/json"
"strings"
)
func stripColonSeparatedPrefix(schema string) string {
colonIdx := strings.Index(schema, ":")
if colonIdx == -1 {
return schema
} else {
return schema[colonIdx+1:]
}
}
type SelfDescribingEvent struct {
Contexts `json:"contexts"`
Payload SelfDescribingPayload `json:"payload"`
}
type SelfDescribingPayload struct {
Schema string `json:"schema"`
Data map[string]interface{} `json:"data"`
}
func (e SelfDescribingPayload) SchemaName() *string {
name := stripColonSeparatedPrefix(e.Schema)
return &name
}
func (e SelfDescribingPayload) PayloadAsByte() ([]byte, error) {
payloadBytes, err := json.Marshal(e.Data)
if err != nil {
return nil, err
}
return payloadBytes, nil
}
func (e SelfDescribingPayload) AsByte() ([]byte, error) {
eventBytes, err := json.Marshal(e)
if err != nil {
return nil, err
}
return eventBytes, nil
}
func (e SelfDescribingPayload) AsMap() (map[string]interface{}, error) {
var m map[string]interface{}
b, err := e.AsByte()
if err != nil {
return nil, err
}
err = json.Unmarshal(b, &m)
if err != nil {
return nil, err
}
return m, nil
}
func (e SelfDescribingPayload) Value() (driver.Value, error) {
b, err := json.Marshal(e)
return string(b), err
}
func (e SelfDescribingPayload) Scan(input interface{}) error {
return json.Unmarshal(input.([]byte), &e)
}
type SelfDescribingContext SelfDescribingPayload