This repository has been archived by the owner on Nov 4, 2021. It is now read-only.
/
create.go
71 lines (64 loc) · 1.63 KB
/
create.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 event
import (
"encoding/json"
"strings"
"time"
cloudevents "github.com/cloudevents/sdk-go/v2"
"github.com/wavesoftware/go-ensure"
)
// NewDefault creates a default CloudEvent.
func NewDefault() *cloudevents.Event {
e := cloudevents.NewEvent()
e.SetType(DefaultType)
e.SetID(NewID())
ensure.NoError(e.SetData(cloudevents.ApplicationJSON, map[string]string{}))
e.SetSource(DefaultSource())
e.SetTime(time.Now())
ensure.NoError(e.Validate())
return &e
}
// CreateFromSpec will create an event by parsing given args.
func CreateFromSpec(spec *Spec) (*cloudevents.Event, error) {
e := NewDefault()
e.SetID(spec.ID)
e.SetSource(spec.Source)
e.SetType(spec.Type)
m := map[string]interface{}{}
for _, fieldSpec := range spec.Fields {
updateMapWithSpec(m, fieldSpec)
}
err := e.SetData(cloudevents.ApplicationJSON, m)
if err != nil {
return nil, err
}
return e, nil
}
func updateMapWithSpec(m map[string]interface{}, spec FieldSpec) {
paths := strings.Split(spec.Path, ".")
curr := m
for i, p := range paths {
if i < len(paths)-1 {
if _, ok := curr[p]; !ok {
curr[p] = map[string]interface{}{}
}
curr = curr[p].(map[string]interface{})
} else {
curr[p] = spec.Value
}
}
}
// UnmarshalData will take bytes and unmarshall it as JSON to map structure.
func UnmarshalData(bytes []byte) (map[string]interface{}, error) {
m := map[string]interface{}{}
err := json.Unmarshal(bytes, &m)
if err != nil {
return nil, err
}
return m, nil
}
// AddField will add a field to the spec.
func (s *Spec) AddField(path string, val interface{}) {
s.Fields = append(s.Fields, FieldSpec{
Path: path, Value: val,
})
}