45 lines
1.0 KiB
Go
45 lines
1.0 KiB
Go
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)
|
||
}
|
||
|
||
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 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
|
||
}
|