Files
backend_v2/internal/repository/user_repository.go
toom1996 74ba700598 update
2026-09-07 00:01:48 +08:00

76 lines
2.1 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)
// SetTier 设置用户等级(free/vip),供后台管理提级 VIP。
SetTier(ctx context.Context, id uint32, tier string) error
// List 列出全量用户(后台管理用),按 id 升序。
List(ctx context.Context) ([]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 (r *userRepository) SetTier(ctx context.Context, id uint32, tier string) error {
return r.db.WithContext(ctx).
Model(&model.User{}).
Where("id = ? AND is_deleted = ?", id, 0).
Update("tier", tier).Error
}
func (r *userRepository) List(ctx context.Context) ([]model.User, error) {
var users []model.User
err := r.db.WithContext(ctx).
Where("is_deleted = ?", 0).
Order("id ASC").
Find(&users).Error
return users, 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
}