-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
60 lines (50 loc) · 1.27 KB
/
main.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
//Event sourcing with hist, minimalist.
package main
import (
"encoding/json"
"fmt"
"reflect"
"github.com/robertreppel/hist/storage/leveldb"
)
const eventDataDirectory = "db"
func main() {
planet, result := createWorld("Earth")
fmt.Printf("Create world: %s\n", result)
save("Earth", planet.changes)
savedEarth := load("Earth")
fmt.Println(savedEarth)
fmt.Printf("Events stored in '%s' directory.\n", eventDataDirectory)
}
func save(planetID string, changes []interface{}) {
eventStore, err := leveldb.Store(eventDataDirectory)
failIf(err)
for _, event := range changes {
jsonEvent, err := json.Marshal(event)
failIf(err)
err = eventStore.Save("world"+"-"+planetID, reflect.TypeOf(event).String(), []byte(jsonEvent))
failIf(err)
}
}
func load(planetID string) *world {
eventStore, err := leveldb.Store(eventDataDirectory)
failIf(err)
eventHistory, err := eventStore.Get("world" + "-" + planetID)
failIf(err)
var events []interface{}
for _, item := range eventHistory {
if item.Type == "main.worldCreated" {
var event worldCreated
err := json.Unmarshal(item.Data, &event)
failIf(err)
events = append(events, event)
}
}
var planet world
planet.loadFromHistory(events)
return &planet
}
func failIf(err error) {
if err != nil {
panic(err)
}
}