topfans/backend/services/aiChatService/repository/config_repository.go
2026-05-28 12:00:19 +08:00

60 lines
1.8 KiB
Go

package repository
import (
"context"
"fmt"
"github.com/topfans/backend/services/aiChatService/model"
"gorm.io/gorm"
)
// ConfigRepository 配置仓库接口
type ConfigRepository interface {
Get(ctx context.Context, key string) (string, error)
GetByCategory(ctx context.Context, category string) (map[string]string, error)
Update(ctx context.Context, key, value string) error
}
// PostgreSQLConfigRepository PostgreSQL 配置仓库实现
type PostgreSQLConfigRepository struct {
db *gorm.DB
}
// NewPostgreSQLConfigRepository 创建配置仓库
func NewPostgreSQLConfigRepository(db *gorm.DB) *PostgreSQLConfigRepository {
return &PostgreSQLConfigRepository{db: db}
}
// Get 获取单个配置值
func (r *PostgreSQLConfigRepository) Get(ctx context.Context, key string) (string, error) {
var config model.Config
if err := r.db.WithContext(ctx).Where("config_key = ?", key).First(&config).Error; err != nil {
if err == gorm.ErrRecordNotFound {
return "", model.ErrConfigNotFound
}
return "", fmt.Errorf("failed to get config: %w", err)
}
return config.ConfigValue, nil
}
// GetByCategory 按分类获取所有配置
func (r *PostgreSQLConfigRepository) GetByCategory(ctx context.Context, category string) (map[string]string, error) {
var configs []model.Config
if err := r.db.WithContext(ctx).Where("category = ?", category).Find(&configs).Error; err != nil {
return nil, fmt.Errorf("failed to get configs: %w", err)
}
result := make(map[string]string)
for _, c := range configs {
result[c.ConfigKey] = c.ConfigValue
}
return result, nil
}
// Update 更新配置值
func (r *PostgreSQLConfigRepository) Update(ctx context.Context, key, value string) error {
return r.db.WithContext(ctx).
Model(&model.Config{}).
Where("config_key = ?", key).
Update("config_value", value).Error
}