-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathserializer.go
80 lines (65 loc) · 1.64 KB
/
serializer.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
package eventsource
import (
"encoding/json"
"reflect"
)
type Serializer interface {
Bind(events ...Event) error
Serialize(event Event) (Record, error)
Deserialize(record Record) (Event, error)
}
type jsonEvent struct {
Type string `json:"t"`
Data json.RawMessage `json:"d"`
}
type jsonSerializer struct {
eventTypes map[string]reflect.Type
}
func (j *jsonSerializer) Bind(events ...Event) error {
for _, event := range events {
eventType, t := EventType(event)
j.eventTypes[eventType] = t
}
return nil
}
func (j *jsonSerializer) Serialize(v Event) (Record, error) {
eventType, _ := EventType(v)
data, err := json.Marshal(v)
if err != nil {
return Record{}, err
}
data, err = json.Marshal(jsonEvent{
Type: eventType,
Data: json.RawMessage(data),
})
if err != nil {
return Record{}, NewError(err, InvalidEncoding, "unable to encode event")
}
return Record{
Version: v.EventVersion(),
At: Time(v.EventAt()),
Data: data,
}, nil
}
func (j *jsonSerializer) Deserialize(record Record) (Event, error) {
wrapper := jsonEvent{}
err := json.Unmarshal(record.Data, &wrapper)
if err != nil {
return nil, NewError(err, InvalidEncoding, "unable to unmarshal event")
}
t, ok := j.eventTypes[wrapper.Type]
if !ok {
return nil, NewError(err, UnboundEventType, "unbound event type, %v", wrapper.Type)
}
v := reflect.New(t).Interface()
err = json.Unmarshal(wrapper.Data, v)
if err != nil {
return nil, NewError(err, InvalidEncoding, "unable to unmarshal event data into %#v", v)
}
return v.(Event), nil
}
func JSONSerializer() Serializer {
return &jsonSerializer{
eventTypes: map[string]reflect.Type{},
}
}