|
|
|
package database
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
|
|
|
|
"git.phc.dm.unipi.it/phc/website/libs/db"
|
|
|
|
"git.phc.dm.unipi.it/phc/website/libs/sl"
|
|
|
|
|
|
|
|
"git.phc.dm.unipi.it/phc/website/server/model"
|
|
|
|
)
|
|
|
|
|
|
|
|
var Slot = sl.NewSlot[Database]()
|
|
|
|
|
|
|
|
// Database is the main database service interface
|
|
|
|
type Database interface {
|
|
|
|
// User
|
|
|
|
|
|
|
|
CreateUser(user model.User) (db.Ref[model.User], error)
|
|
|
|
ReadUser(id db.Ref[model.User]) (model.User, error)
|
|
|
|
ReadUsers() ([]model.User, error)
|
|
|
|
UpdateUser(user model.User) error
|
|
|
|
DeleteUser(id db.Ref[model.User]) error
|
|
|
|
|
|
|
|
// Accounts
|
|
|
|
|
|
|
|
CreateAccount(account model.Account) (db.Ref[model.Account], error)
|
|
|
|
ReadAccount(id db.Ref[model.Account]) (model.Account, error)
|
|
|
|
UpdateAccount(user model.Account) error
|
|
|
|
DeleteAccount(id db.Ref[model.Account]) error
|
|
|
|
|
|
|
|
// Users & Accounts
|
|
|
|
|
|
|
|
ReadUserAccounts(user db.Ref[model.User]) ([]model.Account, error)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Memory is an in-memory implementation of [Database] that can be used for testing
|
|
|
|
type Memory struct {
|
|
|
|
Database // TODO: Per ora almeno così facciamo compilare il codice
|
|
|
|
|
|
|
|
Users []model.User
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *Memory) CreateUser(user model.User) (db.Ref[model.User], error) {
|
|
|
|
m.Users = append(m.Users, user)
|
|
|
|
return db.Ref[model.User](user.Id), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *Memory) ReadUser(id db.Ref[model.User]) (model.User, error) {
|
|
|
|
for _, u := range m.Users {
|
|
|
|
if u.Id == id {
|
|
|
|
return u, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return model.User{}, fmt.Errorf(`no user with id "%s"`, id)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *Memory) ReadUsers() ([]model.User, error) {
|
|
|
|
return m.Users, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *Memory) UpdateUser(user model.User) error {
|
|
|
|
for i, u := range m.Users {
|
|
|
|
if u.Id == user.Id {
|
|
|
|
m.Users[i] = user
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return fmt.Errorf(`no user with id "%s"`, user.Id)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *Memory) DeleteUser(id db.Ref[model.User]) error {
|
|
|
|
for i, u := range m.Users {
|
|
|
|
if u.Id == id {
|
|
|
|
m.Users = append(m.Users[:i], m.Users[i+1:]...)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return fmt.Errorf(`no user with id "%s"`, id)
|
|
|
|
}
|