-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathobject_marshaler.go
58 lines (49 loc) · 1.6 KB
/
object_marshaler.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
package snapshotstore
import (
"encoding/base64"
"encoding/json"
"fmt"
"io"
"time"
"github.com/go-estoria/estoria/snapshotstore"
"github.com/go-estoria/estoria/typeid"
"github.com/gofrs/uuid/v5"
)
type ObjectMarshaler interface {
MarshalObject(snapshot *snapshotstore.AggregateSnapshot) ([]byte, error)
UnmarshalObject(src io.ReadCloser) (*snapshotstore.AggregateSnapshot, error)
}
type JSONObject struct {
AggregateID uuid.UUID `json:"aggregate_id"`
AggregateType string `json:"aggregate_type"`
Version int64 `json:"version"`
Timestamp time.Time `json:"timestamp"`
Data string `json:"data"`
}
type JSONObjectMarshaler struct{}
func (m JSONObjectMarshaler) MarshalObject(snapshot *snapshotstore.AggregateSnapshot) ([]byte, error) {
return json.Marshal(JSONObject{
AggregateID: snapshot.AggregateID.UUID(),
AggregateType: snapshot.AggregateID.TypeName(),
Version: snapshot.AggregateVersion,
Timestamp: snapshot.Timestamp,
Data: base64.StdEncoding.EncodeToString(snapshot.Data),
})
}
func (m JSONObjectMarshaler) UnmarshalObject(src io.ReadCloser) (*snapshotstore.AggregateSnapshot, error) {
var obj JSONObject
err := json.NewDecoder(src).Decode(&obj)
if err != nil {
return nil, err
}
data, err := base64.StdEncoding.DecodeString(obj.Data)
if err != nil {
return nil, fmt.Errorf("decoding base64 event data: %w", err)
}
return &snapshotstore.AggregateSnapshot{
AggregateID: typeid.FromUUID(obj.AggregateType, obj.AggregateID),
AggregateVersion: obj.Version,
Timestamp: obj.Timestamp,
Data: data,
}, nil
}