forked from pocketbase/pocketbase
/
settings_upsert.go
90 lines (74 loc) · 2.62 KB
/
settings_upsert.go
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package forms
import (
"os"
"time"
"github.com/AlperRehaYAZGAN/postgresbase/core"
"github.com/AlperRehaYAZGAN/postgresbase/daos"
"github.com/AlperRehaYAZGAN/postgresbase/models"
"github.com/AlperRehaYAZGAN/postgresbase/models/settings"
"github.com/AlperRehaYAZGAN/postgresbase/tools/types"
"github.com/pocketbase/dbx"
)
// SettingsUpsert is a [settings.Settings] upsert (create/update) form.
type SettingsUpsert struct {
*settings.Settings
app core.App
dao *daos.Dao
}
// NewSettingsUpsert creates a new [SettingsUpsert] form with initializer
// config created from the provided [core.App] instance.
//
// If you want to submit the form as part of a transaction,
// you can change the default Dao via [SetDao()].
func NewSettingsUpsert(app core.App) *SettingsUpsert {
form := &SettingsUpsert{
app: app,
dao: app.Dao(),
}
// load the application settings into the form
form.Settings, _ = app.Settings().Clone()
return form
}
// SetDao replaces the default form Dao instance with the provided one.
func (form *SettingsUpsert) SetDao(dao *daos.Dao) {
form.dao = dao
}
// Validate makes the form validatable by implementing [validation.Validatable] interface.
func (form *SettingsUpsert) Validate() error {
return form.Settings.Validate()
}
// Submit validates the form and upserts the loaded settings.
//
// On success the app settings will be refreshed with the form ones.
//
// You can optionally provide a list of InterceptorFunc to further
// modify the form behavior before persisting it.
func (form *SettingsUpsert) Submit(interceptors ...InterceptorFunc[*settings.Settings]) error {
if err := form.Validate(); err != nil {
return err
}
return runInterceptors(form.Settings, func(s *settings.Settings) error {
form.Settings = s
// persists settings change
encryptionKey := os.Getenv(form.app.EncryptionEnv())
if err := form.dao.SaveSettings(form.Settings, encryptionKey); err != nil {
return err
}
// reload app settings
if err := form.app.RefreshSettings(); err != nil {
return err
}
// try to clear old logs not matching the new settings
createdBefore := time.Now().AddDate(0, 0, -1*form.Settings.Logs.MaxDays).UTC().Format(types.DefaultDateLayout)
expr := dbx.NewExp("[[created]] <= {:date} OR [[level]] < {:level}", dbx.Params{
"date": createdBefore,
"level": form.Settings.Logs.MinLevel,
})
form.app.LogsDao().NonconcurrentDB().Delete((&models.Log{}).TableName(), expr).Execute()
// no logs are allowed -> try to reclaim preserved disk space after the previous delete operation
if form.Settings.Logs.MaxDays == 0 {
form.app.LogsDao().Vacuum()
}
return nil
}, interceptors...)
}