learnsteam-quiz-api/internal/repositories/user.go

91 lines
2.2 KiB
Go
Raw Normal View History

2023-10-19 22:47:12 +09:00
package repositories
import (
2023-11-17 01:38:01 +09:00
"fmt"
"learnsteam/learsteam-quiz-api/internal/models"
2023-10-19 22:47:12 +09:00
"gorm.io/gorm"
)
type userRepository struct {
DB *gorm.DB
}
func NewUserRepository(db *gorm.DB) UserRepository {
return &userRepository{
DB: db,
}
}
type UserRepository interface {
2023-11-17 01:38:01 +09:00
List(string, int, int) (*[]models.User, error)
Total(string) (int64, error)
Find(string) (*models.User, error)
2023-10-19 22:47:12 +09:00
FindByUsername(string) (*models.User, error)
Create(*models.User) (*models.User, error)
Update(*models.User) (*models.User, error)
Delete(string) error
}
2023-11-17 01:38:01 +09:00
func (r *userRepository) List(q string, page int, limit int) (*[]models.User, error) {
2023-10-19 22:47:12 +09:00
var users *[]models.User
2023-11-17 01:38:01 +09:00
var err error
offset := limit * (page - 1)
fmt.Println("q", q)
if q != "" {
err = r.DB.Offset(offset).Limit(limit).Order("name ASC").Where("name LIKE ? OR username LIKE ?", "%"+q+"%", "%"+q+"%").Find(&users).Error
} else {
fmt.Println(" query")
err = r.DB.Offset(offset).Limit(limit).Order("created_at DESC").Find(&users).Error
}
2023-10-19 22:47:12 +09:00
return users, err
}
2023-11-17 01:38:01 +09:00
func (r *userRepository) Total(q string) (int64, error) {
var total int64
var err error
if q != "" {
err = r.DB.Model(&models.User{}).Where("name LIKE ? OR username LIKE ?", "%"+q+"%", "%"+q+"%").Count(&total).Error
} else {
err = r.DB.Model(&models.User{}).Count(&total).Error
}
return total, err
}
func (r *userRepository) Find(id string) (*models.User, error) {
2023-10-19 22:47:12 +09:00
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("username = ?", 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
}