114 lines
2.5 KiB
Go
114 lines
2.5 KiB
Go
package service
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"log/slog"
|
|
|
|
"gitea.michaelthomson.dev/mthomson/habits/internal/user/repository"
|
|
"github.com/gofrs/uuid/v5"
|
|
)
|
|
|
|
var (
|
|
ErrNotFound error = errors.New("user cannot be found")
|
|
)
|
|
|
|
type User struct {
|
|
Id uuid.UUID
|
|
Email string
|
|
HashedPassword string
|
|
}
|
|
|
|
func NewUser(id uuid.UUID, email string, hashedPassword string) User {
|
|
return User{Id: id, Email: email, HashedPassword: hashedPassword}
|
|
}
|
|
|
|
func UserFromUserRow(userRow repository.UserRow) User {
|
|
return User{Id: userRow.Id, Email: userRow.Email, HashedPassword: userRow.HashedPassword}
|
|
}
|
|
|
|
func UserRowFromUser(user User) repository.UserRow {
|
|
return repository.UserRow{Id: user.Id, Email: user.Email, HashedPassword: user.HashedPassword}
|
|
}
|
|
|
|
func (t User) Equal(user User) bool {
|
|
return t.Id == user.Id && t.Email == user.Email && t.HashedPassword == user.HashedPassword
|
|
}
|
|
|
|
type UserRepository interface {
|
|
Create(ctx context.Context, user repository.UserRow) (repository.UserRow, error)
|
|
GetById(ctx context.Context, id uuid.UUID) (repository.UserRow, error)
|
|
Update(ctx context.Context, user repository.UserRow) error
|
|
Delete(ctx context.Context, id uuid.UUID) error
|
|
}
|
|
|
|
type UserService struct {
|
|
logger *slog.Logger
|
|
repo UserRepository
|
|
}
|
|
|
|
func NewUserService(logger *slog.Logger, userRepo UserRepository) *UserService {
|
|
return &UserService{
|
|
logger: logger,
|
|
repo: userRepo,
|
|
}
|
|
}
|
|
|
|
func (s *UserService) GetUser(ctx context.Context, id uuid.UUID) (User, error) {
|
|
user, err := s.repo.GetById(ctx, id)
|
|
|
|
if err != nil {
|
|
if err == repository.ErrNotFound {
|
|
return User{}, ErrNotFound
|
|
}
|
|
|
|
s.logger.ErrorContext(ctx, err.Error())
|
|
return User{}, err
|
|
}
|
|
|
|
return UserFromUserRow(user), err
|
|
}
|
|
|
|
func (s *UserService) CreateUser(ctx context.Context, user User) (User, error) {
|
|
userRow := UserRowFromUser(user)
|
|
|
|
newUserRow, err := s.repo.Create(ctx, userRow)
|
|
|
|
if err != nil {
|
|
s.logger.ErrorContext(ctx, err.Error())
|
|
return User{}, err
|
|
}
|
|
|
|
return UserFromUserRow(newUserRow), err
|
|
}
|
|
|
|
func (s *UserService) DeleteUser(ctx context.Context, id uuid.UUID) error {
|
|
err := s.repo.Delete(ctx, id)
|
|
|
|
if err == repository.ErrNotFound {
|
|
return ErrNotFound
|
|
}
|
|
|
|
if err != nil {
|
|
s.logger.ErrorContext(ctx, err.Error())
|
|
}
|
|
|
|
return err
|
|
}
|
|
|
|
func (s *UserService) UpdateUser(ctx context.Context, user User) error {
|
|
userRow := UserRowFromUser(user)
|
|
|
|
err := s.repo.Update(ctx, userRow)
|
|
|
|
if err == repository.ErrNotFound {
|
|
return ErrNotFound
|
|
}
|
|
|
|
if err != nil {
|
|
s.logger.ErrorContext(ctx, err.Error())
|
|
}
|
|
|
|
return err
|
|
}
|