lens @ master

 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		PreloadVideoMetadata bool
17	}
18
19	SettingsRepository struct {
20		db *gorm.DB
21	}
22)
23
24var _ repository.SettingsRepository = &SettingsRepository{}
25
26func NewSettingsRespository(db *gorm.DB) *SettingsRepository {
27	return &SettingsRepository{
28		db: db,
29	}
30}
31
32func (self *SettingsRepository) ensureSettings(ctx context.Context) (*Settings, error) {
33	var (
34		db = self.db.WithContext(ctx)
35		s  = &Settings{}
36	)
37	result := db.Limit(1).Find(s)
38	if result.Error != nil {
39		return nil, result.Error
40	}
41
42	return s, nil
43}
44
45func (self *SettingsRepository) Save(ctx context.Context, toSaveSettings *repository.Settings) error {
46	db := self.db.WithContext(ctx)
47
48	s, err := self.ensureSettings(ctx)
49	if err != nil {
50		return err
51	}
52
53	s.ShowMode = toSaveSettings.ShowMode
54	s.ShowOwner = toSaveSettings.ShowOwner
55	s.PreloadVideoMetadata = toSaveSettings.PreloadVideoMetadata
56
57	result := db.Save(s)
58	return result.Error
59}
60
61func (self *SettingsRepository) Load(ctx context.Context) (*repository.Settings, error) {
62	s, err := self.ensureSettings(ctx)
63	if err != nil {
64		return nil, err
65	}
66
67	return &repository.Settings{
68		ShowMode:             s.ShowMode,
69		ShowOwner:            s.ShowOwner,
70		PreloadVideoMetadata: s.PreloadVideoMetadata,
71	}, nil
72}