Files
pig-farm-controller/internal/infra/repository/user_repository.go
2025-11-05 23:00:07 +08:00

87 lines
3.1 KiB
Go

// Package repository 提供了数据访问的仓库实现
package repository
import (
"context"
"git.huangwc.com/pig/pig-farm-controller/internal/infra/logs"
"git.huangwc.com/pig/pig-farm-controller/internal/infra/models"
"gorm.io/gorm"
)
// UserRepository 定义了与用户模型相关的数据库操作接口
// 这是为了让业务逻辑层依赖于抽象,而不是具体的数据库实现
type UserRepository interface {
Create(ctx context.Context, user *models.User) error
FindByUsername(ctx context.Context, username string) (*models.User, error)
FindByID(ctx context.Context, id uint) (*models.User, error)
FindUserForLogin(ctx context.Context, identifier string) (*models.User, error)
FindAll(ctx context.Context) ([]*models.User, error)
}
// gormUserRepository 是 UserRepository 的 GORM 实现
type gormUserRepository struct {
ctx context.Context
db *gorm.DB
}
// NewGormUserRepository 创建一个新的 UserRepository GORM 实现实例
func NewGormUserRepository(ctx context.Context, db *gorm.DB) UserRepository {
return &gormUserRepository{ctx: ctx, db: db}
}
// Create 创建一个新的用户记录
func (r *gormUserRepository) Create(ctx context.Context, user *models.User) error {
repoCtx := logs.AddFuncName(ctx, r.ctx, "Create")
// BeforeSave 钩子会在这里被自动触发
return r.db.WithContext(repoCtx).Create(user).Error
}
// FindByUsername 根据用户名查找用户
func (r *gormUserRepository) FindByUsername(ctx context.Context, username string) (*models.User, error) {
repoCtx := logs.AddFuncName(ctx, r.ctx, "FindByUsername")
var user models.User
if err := r.db.WithContext(repoCtx).Where("username = ?", username).First(&user).Error; err != nil {
return nil, err
}
return &user, nil
}
// FindUserForLogin 根据提供的标识符查找用户,可用于登录验证
// 标识符可以是用户名、邮箱、手机号、微信号或飞书账号
func (r *gormUserRepository) FindUserForLogin(ctx context.Context, identifier string) (*models.User, error) {
repoCtx := logs.AddFuncName(ctx, r.ctx, "FindUserForLogin")
var user models.User
// 使用 ->> 操作符来查询 JSONB 字段中的文本值
err := r.db.WithContext(repoCtx).Where(
"username = ? OR contact ->> 'email' = ? OR contact ->> 'phone' = ? OR contact ->> 'wechat' = ? OR contact ->> 'feishu' = ?",
identifier, identifier, identifier, identifier, identifier,
).First(&user).Error
if err != nil {
return nil, err
}
return &user, nil
}
// FindByID 根据 ID 查找用户
func (r *gormUserRepository) FindByID(ctx context.Context, id uint) (*models.User, error) {
repoCtx := logs.AddFuncName(ctx, r.ctx, "FindByID")
var user models.User
if err := r.db.WithContext(repoCtx).First(&user, id).Error; err != nil {
return nil, err
}
return &user, nil
}
// FindAll 返回数据库中的所有用户
func (r *gormUserRepository) FindAll(ctx context.Context) ([]*models.User, error) {
repoCtx := logs.AddFuncName(ctx, r.ctx, "FindAll")
var users []*models.User
if err := r.db.WithContext(repoCtx).Where("1 = 1").Find(&users).Error; err != nil {
return nil, err
}
return users, nil
}