prompt 7
This commit is contained in:
@@ -2,6 +2,8 @@ package repo
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"trustcontact/internal/models"
|
||||
|
||||
@@ -12,6 +14,14 @@ type UserRepo struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
type UserListParams struct {
|
||||
Query string
|
||||
Sort string
|
||||
Dir string
|
||||
Page int
|
||||
PageSize int
|
||||
}
|
||||
|
||||
func NewUserRepo(db *gorm.DB) *UserRepo {
|
||||
return &UserRepo{db: db}
|
||||
}
|
||||
@@ -55,3 +65,65 @@ func (r *UserRepo) UpdatePasswordHash(userID uint, passwordHash string) error {
|
||||
Where("id = ?", userID).
|
||||
Update("password_hash", passwordHash).Error
|
||||
}
|
||||
|
||||
func (r *UserRepo) List(params UserListParams) ([]models.User, int64, error) {
|
||||
query := r.db.Model(&models.User{})
|
||||
|
||||
search := strings.TrimSpace(params.Query)
|
||||
if search != "" {
|
||||
like := "%" + strings.ToLower(search) + "%"
|
||||
query = query.Where("LOWER(name) LIKE ? OR LOWER(email) LIKE ?", like, like)
|
||||
}
|
||||
|
||||
var total int64
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
orderBy := sanitizeSort(params.Sort)
|
||||
orderDir := sanitizeDir(params.Dir)
|
||||
orderClause := fmt.Sprintf("%s %s", orderBy, orderDir)
|
||||
|
||||
page := params.Page
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
pageSize := params.PageSize
|
||||
if pageSize <= 0 {
|
||||
pageSize = 10
|
||||
}
|
||||
if pageSize > 100 {
|
||||
pageSize = 100
|
||||
}
|
||||
|
||||
offset := (page - 1) * pageSize
|
||||
|
||||
var users []models.User
|
||||
if err := query.Order(orderClause).Limit(pageSize).Offset(offset).Find(&users).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
return users, total, nil
|
||||
}
|
||||
|
||||
func sanitizeSort(sort string) string {
|
||||
switch strings.ToLower(strings.TrimSpace(sort)) {
|
||||
case "id":
|
||||
return "id"
|
||||
case "name":
|
||||
return "name"
|
||||
case "email":
|
||||
return "email"
|
||||
default:
|
||||
return "id"
|
||||
}
|
||||
}
|
||||
|
||||
func sanitizeDir(dir string) string {
|
||||
switch strings.ToLower(strings.TrimSpace(dir)) {
|
||||
case "desc":
|
||||
return "desc"
|
||||
default:
|
||||
return "asc"
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user