Files
opencatd-open/internal/service/apikey.go
2025-04-20 16:22:23 +08:00

90 lines
2.3 KiB
Go

package service
import (
"context"
"fmt"
"opencatd-open/internal/dao"
"opencatd-open/internal/model"
"opencatd-open/internal/utils"
"gorm.io/gorm"
)
type ApiKeyServiceImpl struct {
db *gorm.DB
apiKeyRepo dao.ApiKeyRepository
}
func NewApiKeyService(db *gorm.DB, apiKeyDao dao.ApiKeyRepository) *ApiKeyServiceImpl {
return &ApiKeyServiceImpl{db: db, apiKeyRepo: apiKeyDao}
}
func (s *ApiKeyServiceImpl) CreateApiKey(ctx context.Context, apikey *model.ApiKey) error {
return s.apiKeyRepo.Create(apikey)
}
func (s *ApiKeyServiceImpl) GetApiKey(ctx context.Context, id int64) (*model.ApiKey, error) {
return s.apiKeyRepo.GetByID(id)
}
func (s *ApiKeyServiceImpl) ListApiKey(ctx context.Context, limit, offset int, active []string) ([]*model.ApiKey, int64, error) {
var conditions = make(map[string]interface{})
if len(active) > 0 {
conditions["active IN ?"] = utils.StringToBool(active)
}
return s.apiKeyRepo.ListWithFilters(limit, offset, conditions)
}
func (s *ApiKeyServiceImpl) UpdateApiKey(ctx context.Context, apikey *model.ApiKey) error {
_key, err := s.apiKeyRepo.GetByID(apikey.ID)
if err != nil {
return fmt.Errorf("get apikey failed: %v", err)
}
if apikey.ApiKey != nil {
_key.ApiKey = apikey.ApiKey
}
if apikey.Active != nil {
_key.Active = apikey.Active
}
if apikey.Endpoint != nil {
_key.Endpoint = apikey.Endpoint
}
if apikey.ResourceNmae != nil {
_key.ResourceNmae = apikey.ResourceNmae
}
if apikey.AccessKey != nil {
_key.AccessKey = apikey.AccessKey
}
if apikey.SecretKey != nil {
_key.SecretKey = apikey.SecretKey
}
if apikey.ModelAlias != nil {
_key.ModelAlias = apikey.ModelAlias
}
if apikey.ModelPrefix != nil {
_key.ModelPrefix = apikey.ModelPrefix
}
if apikey.Parameters != nil {
_key.Parameters = apikey.Parameters
}
if apikey.SupportModels != nil {
_key.SupportModels = apikey.SupportModels
}
if apikey.SupportModelsArray != nil {
_key.SupportModelsArray = apikey.SupportModelsArray
}
return s.apiKeyRepo.Update(apikey)
}
func (s *ApiKeyServiceImpl) DeleteApiKey(ctx context.Context, ids []int64) error {
return s.apiKeyRepo.BatchDelete(ids)
}
func (s *ApiKeyServiceImpl) EnableApiKey(ctx context.Context, ids []int64) error {
return s.apiKeyRepo.BatchEnable(ids)
}
func (s *ApiKeyServiceImpl) DisableApiKey(ctx context.Context, ids []int64) error {
return s.apiKeyRepo.BatchDisable(ids)
}