38 lines
923 B
Go
38 lines
923 B
Go
// repositories/gorm_user_repository.go
|
|
package repositories
|
|
|
|
import (
|
|
"go-todo-api/models"
|
|
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
// GormUserRepository 是 User Repository 接口的 GORM 实现
|
|
type GormUserRepository struct {
|
|
DB *gorm.DB
|
|
}
|
|
|
|
// NewGormUserRepository 创建 GormUserRepository 的新实例
|
|
func NewGormUserRepository(db *gorm.DB) *GormUserRepository {
|
|
return &GormUserRepository{DB: db}
|
|
}
|
|
|
|
// FindByUsername 根据用户名查找用户
|
|
func (r *GormUserRepository) FindByUsername(username string) (*models.User, error) {
|
|
var user models.User
|
|
result := r.DB.Where("username = ?", username).First(&user)
|
|
if result.Error != nil {
|
|
// 统一返回 GORM 错误,让上层 Service 处理
|
|
return nil, result.Error
|
|
}
|
|
return &user, nil
|
|
}
|
|
|
|
// Create 创建新用户
|
|
func (r *GormUserRepository) Create(user *models.User) error {
|
|
if result := r.DB.Create(user); result.Error != nil {
|
|
return result.Error
|
|
}
|
|
return nil
|
|
}
|