68 lines
1.7 KiB
Go
68 lines
1.7 KiB
Go
package repository
|
|
|
|
import (
|
|
"context"
|
|
|
|
"github.com/google/uuid"
|
|
"gorm.io/gorm"
|
|
"worklog/entities"
|
|
)
|
|
|
|
type UserRepository struct {
|
|
db *gorm.DB
|
|
}
|
|
|
|
var userRepo *UserRepository
|
|
|
|
func GetUserRepo(db *gorm.DB) *UserRepository {
|
|
if userRepo != nil {
|
|
return userRepo
|
|
}
|
|
|
|
userRepo = &UserRepository{
|
|
db: db,
|
|
}
|
|
|
|
return userRepo
|
|
}
|
|
|
|
type User interface {
|
|
GetByEmail(ctx context.Context, email string) (*entities.User, error)
|
|
Create(ctx context.Context, user entities.User) error
|
|
Update(ctx context.Context, user entities.User) error
|
|
Delete(ctx context.Context, id uuid.UUID) error
|
|
List(ctx context.Context, offset int, limit int) ([]entities.User, int64)
|
|
}
|
|
|
|
func (r *UserRepository) Create(ctx context.Context, user *entities.User) error {
|
|
return r.db.WithContext(ctx).Create(user).Error
|
|
}
|
|
|
|
func (r *UserRepository) GetByEmail(ctx context.Context, email string) (*entities.User, error) {
|
|
var user entities.User
|
|
if err := r.db.WithContext(ctx).Where("email = ?", email).First(&user).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
return &user, nil
|
|
}
|
|
|
|
func (r *UserRepository) Update(ctx context.Context, user *entities.User) error {
|
|
return r.db.WithContext(ctx).Save(user).Error
|
|
}
|
|
|
|
func (r *UserRepository) Delete(ctx context.Context, id uuid.UUID) error {
|
|
user := entities.User{ID: id}
|
|
return r.db.WithContext(ctx).Delete(&user).Error
|
|
}
|
|
|
|
func (r *UserRepository) List(ctx context.Context, offset int, limit int) ([]entities.DevUser, int64, error) {
|
|
var users []entities.DevUser // TODO: make sure to make this abstractable
|
|
var totalUserCount int64
|
|
|
|
if err := r.db.WithContext(ctx).Find(&users).Count(&totalUserCount).Offset(offset).Limit(limit); err != nil {
|
|
return nil, 0, err.Error
|
|
}
|
|
|
|
return users, totalUserCount, nil
|
|
}
|