72 lines
1.9 KiB
Go
72 lines
1.9 KiB
Go
package repository
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
|
|
"fashionapi/internal/model"
|
|
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
// UserRepository 用户数据访问接口。
|
|
type UserRepository interface {
|
|
// ExistsByUsernameOrEmail 判断用户名或邮箱是否已被占用。
|
|
ExistsByUsernameOrEmail(ctx context.Context, username, email string) (bool, error)
|
|
// Create 创建用户。
|
|
Create(ctx context.Context, u *model.User) error
|
|
// FindByAccount 按邮箱或用户名查找未删除的用户。不存在时返回 ErrNotFound。
|
|
FindByAccount(ctx context.Context, account string) (*model.User, error)
|
|
// FindByID 按主键查找用户。不存在时返回 ErrNotFound。
|
|
FindByID(ctx context.Context, id uint32) (*model.User, error)
|
|
}
|
|
|
|
type userRepository struct {
|
|
db *gorm.DB
|
|
}
|
|
|
|
// NewUserRepository 创建用户仓储。
|
|
func NewUserRepository(db *gorm.DB) UserRepository {
|
|
return &userRepository{db: db}
|
|
}
|
|
|
|
func (r *userRepository) ExistsByUsernameOrEmail(ctx context.Context, username, email string) (bool, error) {
|
|
var cnt int64
|
|
err := r.db.WithContext(ctx).
|
|
Model(&model.User{}).
|
|
Where("username = ? OR email = ?", username, email).
|
|
Count(&cnt).Error
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
return cnt > 0, nil
|
|
}
|
|
|
|
func (r *userRepository) Create(ctx context.Context, u *model.User) error {
|
|
return r.db.WithContext(ctx).Create(u).Error
|
|
}
|
|
|
|
func (r *userRepository) FindByAccount(ctx context.Context, account string) (*model.User, error) {
|
|
var u model.User
|
|
err := r.db.WithContext(ctx).
|
|
Where("is_deleted = 0 AND (email = ? OR username = ?)", account, account).
|
|
First(&u).Error
|
|
return wrapUser(&u, err)
|
|
}
|
|
|
|
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 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
|
|
}
|