-
Notifications
You must be signed in to change notification settings - Fork 1
/
json_encoder.go
57 lines (46 loc) · 1.2 KB
/
json_encoder.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
package eventstore
import (
"encoding/json"
"reflect"
)
// NewJSONEncoder constructs json encoder
// It receives a slice of event types it should be able to encode/decode
func NewJSONEncoder(events ...any) *JsonEncoder {
enc := JsonEncoder{
types: make(map[string]reflect.Type),
}
for _, evt := range events {
t := reflect.TypeOf(evt)
enc.types[t.Name()] = t
}
return &enc
}
// JsonEncoder provides default json Encoder implementation
// It will marshal and unmarshal events to/from json and store the type name
type JsonEncoder struct {
types map[string]reflect.Type
}
// Encode marshals incoming event to it's json representation
func (e *JsonEncoder) Encode(evt any) (*EncodedEvt, error) {
data, err := json.Marshal(evt)
if err != nil {
return nil, err
}
return &EncodedEvt{
Type: reflect.TypeOf(evt).Name(),
Data: string(data),
}, nil
}
// Decode decodes incoming event to it's corresponding go type
func (e *JsonEncoder) Decode(evt *EncodedEvt) (any, error) {
t, ok := e.types[evt.Type]
if !ok {
return nil, ErrEventNotRegistered
}
v := reflect.New(t)
err := json.Unmarshal([]byte(evt.Data), v.Interface())
if err != nil {
return nil, err
}
return v.Elem().Interface(), nil
}