aboutsummaryrefslogtreecommitdiff
path: root/pkg/database/sql/settings.go
blob: 3f4ad08acee47dfe46a871170f97772cfb10099e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package sql

import (
	"context"

	"gorm.io/gorm"

	"git.sr.ht/~gabrielgio/img/pkg/database/repository"
)

type (
	Settings struct {
		gorm.Model
		ShowMode             bool
		ShowOwner            bool
		PreloadVideoMetadata bool
	}

	SettingsRepository struct {
		db *gorm.DB
	}
)

var _ repository.SettingsRepository = &SettingsRepository{}

func NewSettingsRespository(db *gorm.DB) *SettingsRepository {
	return &SettingsRepository{
		db: db,
	}
}

func (self *SettingsRepository) ensureSettings(ctx context.Context) (*Settings, error) {
	var (
		db = self.db.WithContext(ctx)
		s  = &Settings{}
	)
	result := db.Limit(1).Find(s)
	if result.Error != nil {
		return nil, result.Error
	}

	return s, nil
}

func (self *SettingsRepository) Save(ctx context.Context, toSaveSettings *repository.Settings) error {
	db := self.db.WithContext(ctx)

	s, err := self.ensureSettings(ctx)
	if err != nil {
		return err
	}

	s.ShowMode = toSaveSettings.ShowMode
	s.ShowOwner = toSaveSettings.ShowOwner
	s.PreloadVideoMetadata = toSaveSettings.PreloadVideoMetadata

	result := db.Save(s)
	return result.Error
}

func (self *SettingsRepository) Load(ctx context.Context) (*repository.Settings, error) {
	s, err := self.ensureSettings(ctx)
	if err != nil {
		return nil, err
	}

	return &repository.Settings{
		ShowMode:             s.ShowMode,
		ShowOwner:            s.ShowOwner,
		PreloadVideoMetadata: s.PreloadVideoMetadata,
	}, nil
}