Skip to content

Instantly share code, notes, and snippets.

@hallgren
Created December 17, 2020 07:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hallgren/49b71b09a50e36b5209f03cdf61c58f8 to your computer and use it in GitHub Desktop.
Save hallgren/49b71b09a50e36b5209f03cdf61c58f8 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"errors"
sqldriver "database/sql"
"github.com/hallgren/eventsourcing"
"github.com/davecgh/go-spew/spew"
"github.com/hallgren/eventsourcing/eventstore/sql"
"github.com/hallgren/eventsourcing/serializer/unsafe"
_ "github.com/mattn/go-sqlite3"
)
type Religion int
const (
Atheist Religion = iota
Christian
)
type Person struct {
eventsourcing.AggregateRoot
Name string
Age int
Religion Religion
}
// Transition the person state dependent on the events
func (p *Person) Transition(event eventsourcing.Event) {
switch e := event.Data.(type) {
case *Born:
p.Age = 0
p.Name = e.WorkingName
case *AgedOneYear:
p.Age += 1
case *Baptized:
p.Name = e.Name
p.Religion = Christian
}
}
// Initial event
type Born struct {
WorkingName string
}
// Event that happens once a year
type AgedOneYear struct {}
type Baptized struct {
Name string
}
// CreatePerson constructor for Person
func Birth(name string) (*Person, error) {
if name == "" {
return nil, errors.New("name can't be blank")
}
person := Person{}
person.TrackChange(&person, &Born{WorkingName: name})
return &person, nil
}
func (p *Person) Grow() {
p.TrackChange(p, &AgedOneYear{})
}
func (p *Person) Baptize(name string) {
if p.Religion == Christian {
return
}
p.TrackChange(p, &Baptized{Name: name})
}
func main() {
p, err := Birth("plutten")
if err != nil {
fmt.Println("person not born")
}
p.Grow()
spew.Dump(p.AggregateEvents)
fmt.Println(p.Name)
fmt.Println(p.Religion)
p.Baptize("Carl")
p.Baptize("Victoria")
fmt.Println(p.Name)
fmt.Println(p.Religion)
spew.Dump(p.AggregateEvents)
db, err := sqldriver.Open("sqlite3","db.sqlite3")
es := sql.Open(*db, unsafe.New())
es.Migrate()
repo := eventsourcing.NewRepository(es, nil)
s := repo.SubscriberAggregateType(func(e eventsourcing.Event) {
fmt.Println("sub events", e)
}, &Person{})
s.Subscribe()
s.Unsubscribe()
repo.Save(p)
spew.Dump(p)
p2 := Person{}
repo.Get(p.AggregateID, &p2)
spew.Dump(p2)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment