94 lines
2.4 KiB
Go
94 lines
2.4 KiB
Go
package service
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
|
|
"go-backend-template/internal/contract"
|
|
"go-backend-template/internal/repository"
|
|
"go-backend-template/internal/transformer"
|
|
|
|
"github.com/google/uuid"
|
|
"golang.org/x/crypto/bcrypt"
|
|
)
|
|
|
|
type UserServiceImpl struct {
|
|
userRepo *repository.UserRepositoryImpl
|
|
}
|
|
|
|
func NewUserService(userRepo *repository.UserRepositoryImpl) *UserServiceImpl {
|
|
return &UserServiceImpl{
|
|
userRepo: userRepo,
|
|
}
|
|
}
|
|
|
|
func (s *UserServiceImpl) CreateUser(ctx context.Context, req *contract.CreateUserRequest) (*contract.UserResponse, error) {
|
|
// Check if user already exists
|
|
existingUser, _ := s.userRepo.GetByEmail(ctx, req.Email)
|
|
if existingUser != nil {
|
|
return nil, errors.New("user with this email already exists")
|
|
}
|
|
|
|
// Hash password
|
|
passwordHash, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// Create user entity
|
|
user := transformer.CreateUserRequestToEntity(req, string(passwordHash))
|
|
user.ID = uuid.New()
|
|
|
|
// Save to database
|
|
if err := s.userRepo.Create(ctx, user); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return transformer.EntityToContract(user), nil
|
|
}
|
|
|
|
func (s *UserServiceImpl) GetUserByID(ctx context.Context, id uuid.UUID) (*contract.UserResponse, error) {
|
|
user, err := s.userRepo.GetByID(ctx, id)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return transformer.EntityToContract(user), nil
|
|
}
|
|
|
|
func (s *UserServiceImpl) GetUsers(ctx context.Context, page, limit int) (*contract.PaginatedUserResponse, error) {
|
|
users, totalCount, err := s.userRepo.GetAll(ctx, page, limit)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
userResponses := transformer.EntitiesToContracts(users)
|
|
pagination := transformer.CreatePaginationResponse(int(totalCount), page, limit)
|
|
|
|
return &contract.PaginatedUserResponse{
|
|
Users: userResponses,
|
|
Pagination: pagination,
|
|
}, nil
|
|
}
|
|
|
|
func (s *UserServiceImpl) UpdateUser(ctx context.Context, id uuid.UUID, req *contract.UpdateUserRequest) (*contract.UserResponse, error) {
|
|
user, err := s.userRepo.GetByID(ctx, id)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// Update user fields
|
|
updatedUser := transformer.UpdateUserEntity(user, req)
|
|
|
|
// Save to database
|
|
if err := s.userRepo.Update(ctx, updatedUser); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return transformer.EntityToContract(updatedUser), nil
|
|
}
|
|
|
|
func (s *UserServiceImpl) DeleteUser(ctx context.Context, id uuid.UUID) error {
|
|
return s.userRepo.Delete(ctx, id)
|
|
}
|