forked from pocketbase/pocketbase
-
Notifications
You must be signed in to change notification settings - Fork 0
/
admin_upsert.go
96 lines (82 loc) · 2.5 KB
/
admin_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
91
92
93
94
95
96
package forms
import (
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/go-ozzo/ozzo-validation/v4/is"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/forms/validators"
"github.com/pocketbase/pocketbase/models"
)
// AdminUpsert defines an admin upsert (create/update) form.
type AdminUpsert struct {
app core.App
admin *models.Admin
isCreate bool
Avatar int `form:"avatar" json:"avatar"`
Email string `form:"email" json:"email"`
Password string `form:"password" json:"password"`
PasswordConfirm string `form:"passwordConfirm" json:"passwordConfirm"`
}
// NewAdminUpsert creates new upsert form for the provided admin model
// (pass an empty admin model instance (`&models.Admin{}`) for create).
func NewAdminUpsert(app core.App, admin *models.Admin) *AdminUpsert {
form := &AdminUpsert{
app: app,
admin: admin,
isCreate: !admin.HasId(),
}
// load defaults
form.Avatar = admin.Avatar
form.Email = admin.Email
return form
}
// Validate makes the form validatable by implementing [validation.Validatable] interface.
func (form *AdminUpsert) Validate() error {
return validation.ValidateStruct(form,
validation.Field(
&form.Avatar,
validation.Min(0),
validation.Max(9),
),
validation.Field(
&form.Email,
validation.Required,
validation.Length(1, 255),
is.Email,
validation.By(form.checkUniqueEmail),
),
validation.Field(
&form.Password,
validation.When(form.isCreate, validation.Required),
validation.Length(10, 100),
),
validation.Field(
&form.PasswordConfirm,
validation.When(form.Password != "", validation.Required),
validation.By(validators.Compare(form.Password)),
),
)
}
func (form *AdminUpsert) checkUniqueEmail(value any) error {
v, _ := value.(string)
if form.app.Dao().IsAdminEmailUnique(v, form.admin.Id) {
return nil
}
return validation.NewError("validation_admin_email_exists", "Admin email already exists.")
}
// Submit validates the form and upserts the form admin model.
//
// You can optionally provide a list of InterceptorFunc to further
// modify the form behavior before persisting it.
func (form *AdminUpsert) Submit(interceptors ...InterceptorFunc) error {
if err := form.Validate(); err != nil {
return err
}
form.admin.Avatar = form.Avatar
form.admin.Email = form.Email
if form.Password != "" {
form.admin.SetPassword(form.Password)
}
return runInterceptors(func() error {
return form.app.Dao().SaveAdmin(form.admin)
}, interceptors...)
}