lens @ ff6b55491dec7ad1973dda37a35e2d9f47f75bcb

 1package sql
 2
 3import (
 4	"context"
 5
 6	"gorm.io/gorm"
 7
 8	"git.sr.ht/~gabrielgio/img/pkg/database/repository"
 9)
10
11type (
12	Settings struct {
13		gorm.Model
14		ShowMode  bool
15		ShowOwner bool
16	}
17
18	SettingsRepository struct {
19		db *gorm.DB
20	}
21)
22
23var _ repository.SettingsRepository = &SettingsRepository{}
24
25func NewSettingsRespository(db *gorm.DB) *SettingsRepository {
26	return &SettingsRepository{
27		db: db,
28	}
29}
30
31func (self *SettingsRepository) ensureSettings(ctx context.Context) (*Settings, error) {
32	var (
33		db = self.db.WithContext(ctx)
34		s  = &Settings{}
35	)
36	result := db.Limit(1).Find(s)
37	if result.Error != nil {
38		return nil, result.Error
39	}
40
41	return s, nil
42}
43
44func (self *SettingsRepository) Save(ctx context.Context, toSaveSettings *repository.Settings) error {
45	db := self.db.WithContext(ctx)
46
47	s, err := self.ensureSettings(ctx)
48	if err != nil {
49		return err
50	}
51
52	s.ShowMode = toSaveSettings.ShowMode
53	s.ShowOwner = toSaveSettings.ShowOwner
54
55	result := db.Save(s)
56	return result.Error
57}
58
59func (self *SettingsRepository) Load(ctx context.Context) (*repository.Settings, error) {
60	s, err := self.ensureSettings(ctx)
61	if err != nil {
62		return nil, err
63	}
64
65	return &repository.Settings{
66		ShowMode:  s.ShowMode,
67		ShowOwner: s.ShowOwner,
68	}, nil
69}