lens @ 6e84441dab0a2b89869e33d7e89d14189d9b67c0

  1//go:build unit
  2
  3package service
  4
  5import (
  6	"context"
  7	"errors"
  8
  9	"git.sr.ht/~gabrielgio/img/pkg/database/repository"
 10)
 11
 12type (
 13	User struct {
 14		ID       uint
 15		Username string
 16		Name     string
 17		Password []byte
 18		IsAdmin  bool
 19		Path     string
 20	}
 21
 22	Users map[uint]*User
 23
 24	UserRepository struct {
 25		icount uint
 26		users  Users
 27	}
 28)
 29
 30var _ repository.UserRepository = &UserRepository{}
 31var _ repository.AuthRepository = &UserRepository{}
 32
 33func NewUserRepository() *UserRepository {
 34	return &UserRepository{
 35		users: make(map[uint]*User),
 36	}
 37}
 38
 39func (u *User) ToModel() *repository.User {
 40	return &repository.User{
 41		ID:       u.ID,
 42		Username: u.Username,
 43		Name:     u.Name,
 44		IsAdmin:  u.IsAdmin,
 45		Path:     u.Path,
 46	}
 47}
 48
 49func (u Users) ToModels() []*repository.User {
 50	users := make([]*repository.User, 0, len(u))
 51	for _, i := range u {
 52		users = append(users, i.ToModel())
 53	}
 54	return users
 55}
 56
 57func (u *UserRepository) Get(ctx context.Context, id uint) (*repository.User, error) {
 58	if user, ok := u.users[id]; ok {
 59		return user.ToModel(), nil
 60	}
 61
 62	return nil, errors.New("Not Found")
 63}
 64
 65func (u *UserRepository) List(_ context.Context) ([]*repository.User, error) {
 66	return u.users.ToModels(), nil
 67}
 68
 69func (u *UserRepository) Create(_ context.Context, createUser *repository.CreateUser) (uint, error) {
 70	id := u.furtherID()
 71	u.users[id] = &User{
 72		ID:       id,
 73		Name:     createUser.Name,
 74		Username: createUser.Username,
 75		Path:     createUser.Path,
 76		Password: createUser.Password,
 77	}
 78	return id, nil
 79}
 80
 81func (u *UserRepository) Update(_ context.Context, id uint, updateUser *repository.UpdateUser) error {
 82	user, ok := u.users[id]
 83	if !ok {
 84		return errors.New("Invalid ID")
 85	}
 86
 87	user.Name = updateUser.Name
 88	user.Username = updateUser.Username
 89	if updateUser.Password != "" {
 90		user.Password = []byte(updateUser.Password)
 91	}
 92
 93	return nil
 94}
 95
 96func (u *UserRepository) Any(_ context.Context) (bool, error) {
 97	return len(u.users) > 0, nil
 98}
 99
100func (u *UserRepository) GetIDByUsername(ctx context.Context, username string) (uint, error) {
101	for id, u := range u.users {
102		if u.Username == username {
103			return id, nil
104		}
105	}
106
107	return 0, errors.New("Not Found")
108}
109
110func (u *UserRepository) GetPassword(ctx context.Context, id uint) ([]byte, error) {
111	if user, ok := u.users[id]; ok {
112		return []byte(user.Password), nil
113	}
114
115	return nil, errors.New("Not Found")
116}
117
118func (u *UserRepository) furtherID() uint {
119	u.icount++
120	return u.icount
121}