mirror of
https://github.com/SamyRai/turash.git
synced 2025-12-26 23:01:33 +00:00
46 lines
1.2 KiB
Go
46 lines
1.2 KiB
Go
package repository
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
|
|
"bugulma/backend/internal/domain"
|
|
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type SystemSettingsRepository struct {
|
|
db *gorm.DB
|
|
}
|
|
|
|
func NewSystemSettingsRepository(db *gorm.DB) domain.SystemSettingsRepository {
|
|
return &SystemSettingsRepository{db: db}
|
|
}
|
|
|
|
func (r *SystemSettingsRepository) Get(ctx context.Context, key string) (map[string]any, error) {
|
|
var res struct {
|
|
Key string `gorm:"column:key"`
|
|
Value json.RawMessage `gorm:"column:value"`
|
|
}
|
|
if err := r.db.WithContext(ctx).Table("system_settings").Where("key = ?", key).Take(&res).Error; err != nil {
|
|
if err == gorm.ErrRecordNotFound {
|
|
return nil, nil
|
|
}
|
|
return nil, err
|
|
}
|
|
var m map[string]any
|
|
if err := json.Unmarshal(res.Value, &m); err != nil {
|
|
return nil, err
|
|
}
|
|
return m, nil
|
|
}
|
|
|
|
func (r *SystemSettingsRepository) Set(ctx context.Context, key string, value map[string]any) error {
|
|
b, err := json.Marshal(value)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
// upsert
|
|
return r.db.WithContext(ctx).Exec(`INSERT INTO system_settings(key, value, updated_at) VALUES(?, ?, now()) ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = now()`, key, b).Error
|
|
}
|