You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
90 lines
1.9 KiB
Go
90 lines
1.9 KiB
Go
2 years ago
|
package database
|
||
|
|
||
|
import (
|
||
|
"encoding/json"
|
||
|
"fmt"
|
||
|
"os"
|
||
|
|
||
|
"github.com/aziis98/lupus-lite/model"
|
||
|
"github.com/aziis98/lupus-lite/util"
|
||
|
)
|
||
|
|
||
|
type Database interface {
|
||
|
CreateUser(user model.User) error
|
||
|
GetUsers() ([]model.User, error)
|
||
|
GetUser(username string) (model.User, error)
|
||
|
|
||
|
CreatePartita(partitaConfig model.PartitaConfig) (model.Partita, error)
|
||
|
GetPartita(uid string) (model.Partita, error)
|
||
|
}
|
||
|
|
||
|
type memDB struct {
|
||
|
Users map[string]model.User `json:"users"`
|
||
|
Partite map[string]model.Partita `json:"partite"`
|
||
|
}
|
||
|
|
||
|
func NewInMemoryDB() (Database, error) {
|
||
|
var db memDB
|
||
|
|
||
|
exampleFile, err := os.Open("example-db.local.json")
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
|
||
|
if err := json.NewDecoder(exampleFile).Decode(&db); err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
|
||
|
return &db, nil
|
||
|
}
|
||
|
|
||
|
func (db *memDB) GetUsers() ([]model.User, error) {
|
||
|
users := make([]model.User, 0, len(db.Users))
|
||
|
for _, u := range db.Users {
|
||
|
users = append(users, u)
|
||
|
}
|
||
|
|
||
|
return users, nil
|
||
|
}
|
||
|
|
||
|
func (db *memDB) GetUser(username string) (model.User, error) {
|
||
|
user, ok := db.Users[username]
|
||
|
if !ok {
|
||
|
return model.User{}, fmt.Errorf(`no user with username %q`, username)
|
||
|
}
|
||
|
|
||
|
return user, nil
|
||
|
}
|
||
|
|
||
|
func (db *memDB) CreateUser(user model.User) error {
|
||
|
if _, ok := db.Users[user.Username]; ok {
|
||
|
return fmt.Errorf(`user with username %q already exists`, user.Username)
|
||
|
}
|
||
|
|
||
|
db.Users[user.Username] = user
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
func (db *memDB) CreatePartita(partitaConfig model.PartitaConfig) (model.Partita, error) {
|
||
|
uid := util.GenerateRandomString(12)
|
||
|
partita := model.Partita{
|
||
|
Uid: uid,
|
||
|
Config: partitaConfig,
|
||
|
Players: []string{},
|
||
|
Iniziata: false,
|
||
|
}
|
||
|
|
||
|
db.Partite[uid] = partita
|
||
|
|
||
|
return partita, nil
|
||
|
}
|
||
|
|
||
|
func (db *memDB) GetPartita(uid string) (model.Partita, error) {
|
||
|
partita, ok := db.Partite[uid]
|
||
|
if !ok {
|
||
|
return model.Partita{}, fmt.Errorf(`nessuna partita con uid %q`, uid)
|
||
|
}
|
||
|
|
||
|
return partita, nil
|
||
|
}
|