cslms-api/internal/repositories/user.go

95 lines
2.6 KiB
Go
Raw Normal View History

2023-12-27 17:31:49 +09:00
package repositories
import (
"fmt"
"learnsteam/cslms-api/internal/models"
"gorm.io/gorm"
)
type userRepository struct {
DB *gorm.DB
}
func NewUserRepository(db *gorm.DB) UserRepository {
return &userRepository{
DB: db,
}
}
type UserRepository interface {
List(string, int, int) (*[]models.User, error)
Total(string) (int64, error)
Find(int64) (*models.User, error)
FindByUsername(string) (*models.User, error)
Create(*models.User) (*models.User, error)
Update(*models.User) (*models.User, error)
Delete(string) error
}
func (r *userRepository) List(q string, page int, limit int) (*[]models.User, error) {
var users *[]models.User
var err error
offset := limit * (page - 1)
fmt.Println("q", q)
if q != "" {
2024-01-29 17:56:39 +09:00
err = r.DB.Offset(offset).Limit(limit).Order("last_name ASC, first_name ASC").Where("user_role = ?", "member").
Where("first_name LIKE ? OR last_name LIKE ? OR CONCAT(last_name, first_name) LIKE ? OR user_name LIKE ?", "%"+q+"%", "%"+q+"%", "%"+q+"%", "%"+q+"%").
Find(&users).Error
2023-12-27 17:31:49 +09:00
} else {
fmt.Println(" query")
err = r.DB.Offset(offset).Limit(limit).Order("last_name ASC, first_name ASC").Where("user_role = ?", "member").Find(&users).Error
}
return users, err
}
func (r *userRepository) Total(q string) (int64, error) {
var total int64
var err error
if q != "" {
2024-01-29 17:56:39 +09:00
err = r.DB.Model(&models.User{}).Where("user_role = ?", "member").
Where("first_name LIKE ? OR last_name LIKE ? OR CONCAT(last_name, first_name) LIKE ? OR user_name LIKE ?", "%"+q+"%", "%"+q+"%", "%"+q+"%", "%"+q+"%").
Count(&total).Error
2023-12-27 17:31:49 +09:00
} else {
err = r.DB.Model(&models.User{}).Where("user_role = ?", "member").Count(&total).Error
}
return total, err
}
func (r *userRepository) Find(id int64) (*models.User, error) {
var user *models.User
err := r.DB.Where("id = ?", id).First(&user).Error
return user, err
}
func (r *userRepository) FindByUsername(username string) (*models.User, error) {
var user *models.User
err := r.DB.Where("user_name = ?", username).First(&user).Error
return user, err
}
func (r *userRepository) Create(user *models.User) (*models.User, error) {
err := r.DB.Create(&user).Error
return user, err
}
func (r *userRepository) Update(user *models.User) (*models.User, error) {
var row *models.User
if err := r.DB.Where("id=?", user.ID).First(&row).Error; err != nil {
return nil, err
}
err := r.DB.Model(&row).Select("*").Updates(&user).Error
return row, err
}
func (r *userRepository) Delete(id string) error {
var user *models.User
if err := r.DB.Where("id=?", id).First(&user).Error; err != nil {
return err
}
err := r.DB.Delete(&user).Error
return err
}