70 lines
2.0 KiB
Go
70 lines
2.0 KiB
Go
|
|
package services
|
|||
|
|
|
|||
|
|
import (
|
|||
|
|
"context"
|
|||
|
|
"fmt"
|
|||
|
|
"tyapi-server/internal/domains/api/entities"
|
|||
|
|
repo "tyapi-server/internal/domains/api/repositories"
|
|||
|
|
|
|||
|
|
"gorm.io/gorm"
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
// ApiCallAggregateService 聚合服务,管理ApiCall生命周期
|
|||
|
|
type ApiCallAggregateService interface {
|
|||
|
|
CreateApiCall(accessId, requestParams, clientIp string) (*entities.ApiCall, error)
|
|||
|
|
LoadApiCall(ctx context.Context, id string) (*entities.ApiCall, error)
|
|||
|
|
SaveApiCall(ctx context.Context, call *entities.ApiCall) error
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
type ApiCallAggregateServiceImpl struct {
|
|||
|
|
apiUserRepo repo.ApiUserRepository
|
|||
|
|
apiCallRepo repo.ApiCallRepository
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
func NewApiCallAggregateService(apiUserRepo repo.ApiUserRepository, apiCallRepo repo.ApiCallRepository) ApiCallAggregateService {
|
|||
|
|
return &ApiCallAggregateServiceImpl{
|
|||
|
|
apiUserRepo: apiUserRepo,
|
|||
|
|
apiCallRepo: apiCallRepo,
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// NewApiCall 创建ApiCall
|
|||
|
|
func (s *ApiCallAggregateServiceImpl) CreateApiCall(accessId, requestParams, clientIp string) (*entities.ApiCall, error) {
|
|||
|
|
return entities.NewApiCall(accessId, requestParams, clientIp)
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// GetApiCallById 查询ApiCall
|
|||
|
|
func (s *ApiCallAggregateServiceImpl) LoadApiCall(ctx context.Context, id string) (*entities.ApiCall, error) {
|
|||
|
|
return s.apiCallRepo.FindById(ctx, id)
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// SaveApiCall 保存ApiCall
|
|||
|
|
func (s *ApiCallAggregateServiceImpl) SaveApiCall(ctx context.Context, call *entities.ApiCall) error {
|
|||
|
|
// 先尝试查找现有记录
|
|||
|
|
existingCall, err := s.apiCallRepo.FindById(ctx, call.ID)
|
|||
|
|
if err != nil {
|
|||
|
|
if err == gorm.ErrRecordNotFound {
|
|||
|
|
// 记录不存在,执行创建
|
|||
|
|
err = s.apiCallRepo.Create(ctx, call)
|
|||
|
|
if err != nil {
|
|||
|
|
return fmt.Errorf("创建ApiCall失败: %w", err)
|
|||
|
|
}
|
|||
|
|
return nil
|
|||
|
|
}
|
|||
|
|
// 其他错误
|
|||
|
|
return fmt.Errorf("查询ApiCall失败: %w", err)
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 记录存在,执行更新
|
|||
|
|
if existingCall != nil {
|
|||
|
|
err = s.apiCallRepo.Update(ctx, call)
|
|||
|
|
if err != nil {
|
|||
|
|
return fmt.Errorf("更新ApiCall失败: %w", err)
|
|||
|
|
}
|
|||
|
|
return nil
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 理论上不会到达这里,但为了安全起见
|
|||
|
|
return s.apiCallRepo.Create(ctx, call)
|
|||
|
|
}
|