f
This commit is contained in:
@@ -2,10 +2,14 @@ package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"hyapi-server/internal/config"
|
||||
"hyapi-server/internal/domains/api/entities"
|
||||
repo "hyapi-server/internal/domains/api/repositories"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type ApiUserAggregateService interface {
|
||||
@@ -30,6 +34,15 @@ func NewApiUserAggregateService(repo repo.ApiUserRepository, cfg *config.Config)
|
||||
}
|
||||
|
||||
func (s *ApiUserAggregateServiceImpl) CreateApiUser(ctx context.Context, apiUserId string) error {
|
||||
// 已存在则幂等成功,避免重复 INSERT 导致 PostgreSQL 事务中止(SQLSTATE 25P02)
|
||||
existing, err := s.repo.FindByUserId(ctx, apiUserId)
|
||||
if err == nil && existing != nil {
|
||||
return nil
|
||||
}
|
||||
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return err
|
||||
}
|
||||
|
||||
apiUser, err := entities.NewApiUser(apiUserId, s.cfg.Wallet.BalanceAlert.DefaultEnabled, s.cfg.Wallet.BalanceAlert.DefaultThreshold)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -52,16 +52,20 @@ func NewWalletAggregateService(
|
||||
}
|
||||
}
|
||||
|
||||
// CreateWallet 创建钱包
|
||||
// CreateWallet 创建钱包(已存在则幂等返回已有钱包,避免重复 INSERT 中止事务)
|
||||
func (s *WalletAggregateServiceImpl) CreateWallet(ctx context.Context, userID string) (*entities.Wallet, error) {
|
||||
// 检查是否已存在
|
||||
w, _ := s.walletRepo.GetByUserID(ctx, userID)
|
||||
if w != nil {
|
||||
return nil, fmt.Errorf("用户已存在钱包")
|
||||
w, err := s.walletRepo.GetByUserID(ctx, userID)
|
||||
if err == nil && w != nil {
|
||||
return w, nil
|
||||
}
|
||||
wallet := entities.NewWallet(userID, decimal.NewFromFloat(s.cfg.Wallet.DefaultCreditLimit))
|
||||
created, err := s.walletRepo.Create(ctx, *wallet)
|
||||
if err != nil {
|
||||
// 并发下可能已创建成功,再查一次
|
||||
if existing, getErr := s.walletRepo.GetByUserID(ctx, userID); getErr == nil && existing != nil {
|
||||
return existing, nil
|
||||
}
|
||||
s.logger.Error("创建钱包失败", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user