mirror of
https://github.com/SamyRai/tercul-backend.git
synced 2025-12-27 00:31:35 +00:00
63 lines
1.8 KiB
Go
63 lines
1.8 KiB
Go
package repositories
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"gorm.io/gorm"
|
|
models2 "tercul/internal/models"
|
|
)
|
|
|
|
// UserRepository defines CRUD methods specific to User.
|
|
type UserRepository interface {
|
|
BaseRepository[models2.User]
|
|
FindByUsername(ctx context.Context, username string) (*models2.User, error)
|
|
FindByEmail(ctx context.Context, email string) (*models2.User, error)
|
|
ListByRole(ctx context.Context, role models2.UserRole) ([]models2.User, error)
|
|
}
|
|
|
|
type userRepository struct {
|
|
BaseRepository[models2.User]
|
|
db *gorm.DB
|
|
}
|
|
|
|
// NewUserRepository creates a new UserRepository.
|
|
func NewUserRepository(db *gorm.DB) UserRepository {
|
|
return &userRepository{
|
|
BaseRepository: NewBaseRepositoryImpl[models2.User](db),
|
|
db: db,
|
|
}
|
|
}
|
|
|
|
// FindByUsername finds a user by username
|
|
func (r *userRepository) FindByUsername(ctx context.Context, username string) (*models2.User, error) {
|
|
var user models2.User
|
|
if err := r.db.WithContext(ctx).Where("username = ?", username).First(&user).Error; err != nil {
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return nil, ErrEntityNotFound
|
|
}
|
|
return nil, err
|
|
}
|
|
return &user, nil
|
|
}
|
|
|
|
// FindByEmail finds a user by email
|
|
func (r *userRepository) FindByEmail(ctx context.Context, email string) (*models2.User, error) {
|
|
var user models2.User
|
|
if err := r.db.WithContext(ctx).Where("email = ?", email).First(&user).Error; err != nil {
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return nil, ErrEntityNotFound
|
|
}
|
|
return nil, err
|
|
}
|
|
return &user, nil
|
|
}
|
|
|
|
// ListByRole lists users by role
|
|
func (r *userRepository) ListByRole(ctx context.Context, role models2.UserRole) ([]models2.User, error) {
|
|
var users []models2.User
|
|
if err := r.db.WithContext(ctx).Where("role = ?", role).Find(&users).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
return users, nil
|
|
}
|