Files
backend_v2/internal/repository/user_repository.go
toom1996 f4f6e02e3c update
2026-08-31 19:59:56 +08:00

56 lines
1.5 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package repository
import (
"context"
"errors"
"fashionapi/internal/model"
"gorm.io/gorm"
)
// UserRepository 用户数据访问接口。
//
// 当前只保留 FindByID(供 /auth/me 取当前用户)。
// ExistsByUsernameOrEmail / Create / FindByAccount 是注册登录专用,已随路由下线一并删除。
type UserRepository interface {
// FindByID 按主键查找用户。不存在时返回 ErrNotFound。
FindByID(ctx context.Context, id uint32) (*model.User, error)
// FindByAccount 按用户名或邮箱查找(忽略已删除账号),供登录校验。
FindByAccount(ctx context.Context, account string) (*model.User, error)
}
type userRepository struct {
db *gorm.DB
}
// NewUserRepository 创建用户仓储。
func NewUserRepository(db *gorm.DB) UserRepository {
return &userRepository{db: db}
}
func (r *userRepository) FindByID(ctx context.Context, id uint32) (*model.User, error) {
var u model.User
err := r.db.WithContext(ctx).First(&u, id).Error
return wrapUser(&u, err)
}
func (r *userRepository) FindByAccount(ctx context.Context, account string) (*model.User, error) {
var u model.User
err := r.db.WithContext(ctx).
Where("username = ? OR email = ?", account, account).
Where("is_deleted = ?", 0).
First(&u).Error
return wrapUser(&u, err)
}
func wrapUser(u *model.User, err error) (*model.User, error) {
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrNotFound
}
return nil, err
}
return u, nil
}