1
0
mirror of https://github.com/pocketbase/pocketbase.git synced 2024-11-25 09:21:11 +02:00
pocketbase/forms/settings_upsert.go

79 lines
2.0 KiB
Go
Raw Normal View History

2022-07-06 23:19:05 +02:00
package forms
import (
"os"
"time"
"github.com/pocketbase/pocketbase/core"
2022-08-07 14:38:21 +02:00
"github.com/pocketbase/pocketbase/daos"
2022-07-06 23:19:05 +02:00
"github.com/pocketbase/pocketbase/models"
)
2022-10-30 10:28:14 +02:00
// SettingsUpsert is a [core.Settings] upsert (create/update) form.
2022-07-06 23:19:05 +02:00
type SettingsUpsert struct {
*core.Settings
2022-10-30 10:28:14 +02:00
app core.App
dao *daos.Dao
2022-08-07 14:38:21 +02:00
}
// NewSettingsUpsert creates a new [SettingsUpsert] form with initializer
// config created from the provided [core.App] instance.
//
2022-10-30 10:28:14 +02:00
// If you want to submit the form as part of a transaction,
// you can change the default Dao via [SetDao()].
2022-07-06 23:19:05 +02:00
func NewSettingsUpsert(app core.App) *SettingsUpsert {
2022-10-30 10:28:14 +02:00
form := &SettingsUpsert{
app: app,
dao: app.Dao(),
2022-08-07 14:38:21 +02:00
}
2022-07-06 23:19:05 +02:00
// load the application settings into the form
2022-10-30 10:28:14 +02:00
form.Settings, _ = app.Settings().Clone()
2022-07-06 23:19:05 +02:00
return form
}
2022-10-30 10:28:14 +02:00
// SetDao replaces the default form Dao instance with the provided one.
func (form *SettingsUpsert) SetDao(dao *daos.Dao) {
form.dao = dao
}
2022-07-06 23:19:05 +02:00
// 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) error {
2022-07-06 23:19:05 +02:00
if err := form.Validate(); err != nil {
return err
}
2022-10-30 10:28:14 +02:00
encryptionKey := os.Getenv(form.app.EncryptionEnv())
2022-07-06 23:19:05 +02:00
return runInterceptors(func() error {
2022-10-30 10:28:14 +02:00
saveErr := form.dao.SaveParam(
models.ParamAppSettings,
form.Settings,
encryptionKey,
)
if saveErr != nil {
return saveErr
}
2022-07-06 23:19:05 +02:00
// explicitly trigger old logs deletion
2022-10-30 10:28:14 +02:00
form.app.LogsDao().DeleteOldRequests(
time.Now().AddDate(0, 0, -1*form.Settings.Logs.MaxDays),
)
2022-07-06 23:19:05 +02:00
// merge the application settings with the form ones
2022-10-30 10:28:14 +02:00
return form.app.Settings().Merge(form.Settings)
}, interceptors...)
2022-07-06 23:19:05 +02:00
}