You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
87 lines
2.4 KiB
87 lines
2.4 KiB
package model
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
// AIApiKeyInsert 插入AI API密钥
|
|
func AIApiKeyInsert(ctx context.Context, db *gorm.DB, apiKey *AIApiKey) (int64, error) {
|
|
result := db.WithContext(ctx).Create(apiKey)
|
|
if result.Error != nil {
|
|
return 0, result.Error
|
|
}
|
|
return apiKey.Id, nil
|
|
}
|
|
|
|
// AIApiKeyFindOne 根据ID查询AI API密钥
|
|
func AIApiKeyFindOne(ctx context.Context, db *gorm.DB, id int64) (*AIApiKey, error) {
|
|
var apiKey AIApiKey
|
|
result := db.WithContext(ctx).First(&apiKey, id)
|
|
if result.Error != nil {
|
|
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
|
|
return nil, ErrNotFound
|
|
}
|
|
return nil, result.Error
|
|
}
|
|
return &apiKey, nil
|
|
}
|
|
|
|
// AIApiKeyFindList 查询AI API密钥列表(分页)
|
|
func AIApiKeyFindList(ctx context.Context, db *gorm.DB, page, pageSize int64) ([]AIApiKey, int64, error) {
|
|
var apiKeys []AIApiKey
|
|
var total int64
|
|
|
|
query := db.WithContext(ctx).Model(&AIApiKey{})
|
|
|
|
if err := query.Count(&total).Error; err != nil {
|
|
return nil, 0, err
|
|
}
|
|
|
|
offset := (page - 1) * pageSize
|
|
if offset < 0 {
|
|
offset = 0
|
|
}
|
|
err := query.Order("created_at DESC").Offset(int(offset)).Limit(int(pageSize)).Find(&apiKeys).Error
|
|
if err != nil {
|
|
return nil, 0, err
|
|
}
|
|
|
|
return apiKeys, total, nil
|
|
}
|
|
|
|
// AIApiKeyUpdate 更新AI API密钥
|
|
func AIApiKeyUpdate(ctx context.Context, db *gorm.DB, apiKey *AIApiKey) error {
|
|
result := db.WithContext(ctx).Save(apiKey)
|
|
return result.Error
|
|
}
|
|
|
|
// AIApiKeyDelete 删除AI API密钥
|
|
func AIApiKeyDelete(ctx context.Context, db *gorm.DB, id int64) error {
|
|
result := db.WithContext(ctx).Delete(&AIApiKey{}, id)
|
|
return result.Error
|
|
}
|
|
|
|
// AIApiKeyFindByProviderAndUser 根据供应商ID和用户ID查询API密钥
|
|
func AIApiKeyFindByProviderAndUser(ctx context.Context, db *gorm.DB, providerId, userId int64) ([]AIApiKey, error) {
|
|
var apiKeys []AIApiKey
|
|
err := db.WithContext(ctx).Where("provider_id = ? AND user_id = ?", providerId, userId).
|
|
Order("created_at DESC").Find(&apiKeys).Error
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return apiKeys, nil
|
|
}
|
|
|
|
// AIApiKeyFindSystemKeys 查询系统级API密钥(userId=0为系统密钥)
|
|
func AIApiKeyFindSystemKeys(ctx context.Context, db *gorm.DB, providerId int64) ([]AIApiKey, error) {
|
|
var apiKeys []AIApiKey
|
|
err := db.WithContext(ctx).Where("provider_id = ? AND user_id = 0", providerId).
|
|
Order("created_at DESC").Find(&apiKeys).Error
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return apiKeys, nil
|
|
}
|
|
|