2023-10-19 21:15:55 +00:00
|
|
|
package store
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
|
|
|
|
"git.t-juice.club/microfilm/users"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
ErrNoSuchUser = fmt.Errorf("no such user")
|
|
|
|
ErrUserExists = fmt.Errorf("user alread exists")
|
|
|
|
)
|
|
|
|
|
|
|
|
type MemoryStore struct {
|
|
|
|
Users map[string]users.User
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewMemoryStore() *MemoryStore {
|
|
|
|
return &MemoryStore{
|
|
|
|
Users: make(map[string]users.User),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *MemoryStore) AddUser(u users.User) error {
|
|
|
|
if _, ok := s.Users[u.ID]; ok {
|
|
|
|
return ErrUserExists
|
|
|
|
}
|
|
|
|
|
|
|
|
s.Users[u.ID] = u
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *MemoryStore) DeleteUser(id string) error {
|
|
|
|
if _, ok := s.Users[id]; !ok {
|
|
|
|
return ErrNoSuchUser
|
|
|
|
}
|
|
|
|
|
|
|
|
delete(s.Users, id)
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *MemoryStore) UpdateUser(u users.User) error {
|
|
|
|
if _, ok := s.Users[u.ID]; !ok {
|
|
|
|
return ErrNoSuchUser
|
|
|
|
}
|
|
|
|
|
|
|
|
s.Users[u.ID] = u
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-10-21 00:15:19 +00:00
|
|
|
func (s *MemoryStore) GetUser(identifier string) (users.User, error) {
|
|
|
|
u, ok := s.Users[identifier]
|
2023-10-19 21:15:55 +00:00
|
|
|
if !ok {
|
2023-10-21 00:15:19 +00:00
|
|
|
// Check if identifier is username
|
|
|
|
for _, u := range s.Users {
|
|
|
|
if u.Username == identifier {
|
|
|
|
return u, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-10-19 21:15:55 +00:00
|
|
|
return u, ErrNoSuchUser
|
|
|
|
}
|
|
|
|
|
|
|
|
return u, nil
|
|
|
|
}
|