- Updated main.go to initialize email service and include it in the dependency injection container. - Refactored handlers to utilize context in service method calls, improving consistency and error handling. - Introduced new service options for upload, security, and captcha services, enhancing modularity and testability. - Removed unused repository implementations to streamline the codebase. This commit continues the effort to improve the architecture by ensuring all services are properly injected and utilized across the application.
76 lines
1.4 KiB
Go
76 lines
1.4 KiB
Go
package repository
|
|
|
|
import (
|
|
"errors"
|
|
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
// IsNotFound 检查是否为记录未找到错误
|
|
func IsNotFound(err error) bool {
|
|
return errors.Is(err, gorm.ErrRecordNotFound)
|
|
}
|
|
|
|
// HandleNotFound 处理记录未找到的情况,未找到时返回 nil, nil
|
|
func HandleNotFound[T any](result *T, err error) (*T, error) {
|
|
if err != nil {
|
|
if IsNotFound(err) {
|
|
return nil, nil
|
|
}
|
|
return nil, err
|
|
}
|
|
return result, nil
|
|
}
|
|
|
|
// Paginate 创建分页查询
|
|
func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
|
|
return func(db *gorm.DB) *gorm.DB {
|
|
if page < 1 {
|
|
page = 1
|
|
}
|
|
if pageSize < 1 {
|
|
pageSize = 20
|
|
}
|
|
if pageSize > 100 {
|
|
pageSize = 100
|
|
}
|
|
offset := (page - 1) * pageSize
|
|
return db.Offset(offset).Limit(pageSize)
|
|
}
|
|
}
|
|
|
|
// PaginatedQuery 执行分页查询,返回列表和总数
|
|
func PaginatedQuery[T any](
|
|
baseQuery *gorm.DB,
|
|
page, pageSize int,
|
|
orderBy string,
|
|
preloads ...string,
|
|
) ([]T, int64, error) {
|
|
var items []T
|
|
var total int64
|
|
|
|
// 获取总数
|
|
if err := baseQuery.Count(&total).Error; err != nil {
|
|
return nil, 0, err
|
|
}
|
|
|
|
// 分页查询
|
|
query := baseQuery.Scopes(Paginate(page, pageSize))
|
|
|
|
// 添加排序
|
|
if orderBy != "" {
|
|
query = query.Order(orderBy)
|
|
}
|
|
|
|
// 添加预加载
|
|
for _, preload := range preloads {
|
|
query = query.Preload(preload)
|
|
}
|
|
|
|
if err := query.Find(&items).Error; err != nil {
|
|
return nil, 0, err
|
|
}
|
|
|
|
return items, total, nil
|
|
}
|