create basic controller
This commit is contained in:
@@ -0,0 +1,56 @@
|
||||
package game
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/iliadenisov/galaxy/pkg/repo"
|
||||
)
|
||||
|
||||
type ctrl struct {
|
||||
param Param
|
||||
repo Repo
|
||||
}
|
||||
|
||||
type Param struct {
|
||||
StoragePath string
|
||||
}
|
||||
|
||||
func ComposeGame(configure func(*Param), races []string) (gameID uuid.UUID, err error) {
|
||||
control(configure, func(c *ctrl) { c.execute(func(r Repo) { gameID, err = newGame(r, races) }) })
|
||||
return
|
||||
}
|
||||
|
||||
func newController(configure func(*Param)) (*ctrl, error) {
|
||||
c := &Param{
|
||||
StoragePath: ".",
|
||||
}
|
||||
if configure != nil {
|
||||
configure(c)
|
||||
}
|
||||
r, err := repo.NewFileRepo(c.StoragePath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &ctrl{
|
||||
param: *c,
|
||||
repo: r,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func control(configure func(*Param), consumer func(*ctrl)) error {
|
||||
c, err := newController(configure)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
consumer(c)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *ctrl) execute(consumer func(Repo)) error {
|
||||
if err := c.repo.Lock(); err != nil {
|
||||
return fmt.Errorf("execute: lock failed: %s", err)
|
||||
}
|
||||
consumer(c.repo)
|
||||
return c.repo.Release()
|
||||
}
|
||||
Reference in New Issue
Block a user