setplayers, sethost
parent
17c0e2c259
commit
53ca14a1bb
|
|
@ -7,10 +7,30 @@ import (
|
|||
"math/rand"
|
||||
)
|
||||
|
||||
func (p *PriceIsWrong) Players(ctx context.Context, ids []int) error {
|
||||
func (p *PriceIsWrong) apply(e priceiswrong.Event) error {
|
||||
switch e := e.(type) {
|
||||
case *priceiswrong.Host:
|
||||
p.Host = e.ID
|
||||
case *priceiswrong.Players:
|
||||
p.Contestants = p.Contestants[:0]
|
||||
for _, id := range e.IDs {
|
||||
p.Contestants = append(p.Contestants, Player{ID: id})
|
||||
}
|
||||
if n := len(p.Contestants); n > 0 {
|
||||
p.Host = p.Contestants[rand.Intn(n)].ID
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *PriceIsWrong) SetPlayers(ctx context.Context, ids []int) error {
|
||||
return p.upsertEvent(ctx, &priceiswrong.Players{IDs: ids})
|
||||
}
|
||||
|
||||
func (p *PriceIsWrong) SetHost(ctx context.Context, id int) error {
|
||||
return p.upsertEvent(ctx, &priceiswrong.Host{ID: id})
|
||||
}
|
||||
|
||||
func (p *PriceIsWrong) upsertEvent(ctx context.Context, e priceiswrong.Event) error {
|
||||
if err := upsertEvent(ctx, p.id, e); err != nil {
|
||||
return err
|
||||
|
|
@ -36,17 +56,3 @@ func upsertEvent(ctx context.Context, priceIsWrongID int, e priceiswrong.Event)
|
|||
`, priceIsWrongID, b)
|
||||
return err
|
||||
}
|
||||
|
||||
func (p *PriceIsWrong) apply(e priceiswrong.Event) error {
|
||||
switch e := e.(type) {
|
||||
case *priceiswrong.Players:
|
||||
p.Contestants = p.Contestants[:0]
|
||||
for _, id := range e.IDs {
|
||||
p.Contestants = append(p.Contestants, Player{ID: id})
|
||||
}
|
||||
if n := len(p.Contestants); n > 0 {
|
||||
p.Host = p.Contestants[rand.Intn(n)].ID
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,9 +11,14 @@ type Players struct {
|
|||
IDs []int
|
||||
}
|
||||
|
||||
type Host struct {
|
||||
ID int
|
||||
}
|
||||
|
||||
func ParseEvent(b []byte) (Event, error) {
|
||||
typesToPointers := map[string]any{
|
||||
"*priceiswrong.Players": &Players{},
|
||||
"*priceiswrong.Host": &Host{},
|
||||
}
|
||||
t, err := event.Parse(b, typesToPointers)
|
||||
return typesToPointers[t], err
|
||||
|
|
|
|||
|
|
@ -14,11 +14,15 @@ func TestPriceIsWrong(t *testing.T) {
|
|||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := p.Players(ctx, []int{4, 5, 6}); err != nil {
|
||||
if err := p.SetPlayers(ctx, []int{4, 5, 6}); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if len(p.Contestants) != 3 {
|
||||
t.Errorf("bad contestants: %+v", p.Contestants)
|
||||
} else if p.Host < 4 || p.Host > 6 {
|
||||
t.Errorf("bad host: %+v", p.Host)
|
||||
} else if err := p.SetHost(ctx, 5); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if p.Host != 5 {
|
||||
t.Errorf("bad host: %+v", p.Host)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue