This repository has been archived by the owner on Feb 24, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 573
/
user.go
79 lines (70 loc) · 1.95 KB
/
user.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
package models
import (
"encoding/json"
"time"
"github.com/markbates/going/validate"
"github.com/markbates/going/validate/validators"
"github.com/markbates/pop"
)
type User struct {
ID int `json:"id" db:"id"`
CreatedAt time.Time `json:"created_at" db:"created_at"`
UpdatedAt time.Time `json:"updated_at" db:"updated_at"`
FirstName string `json:"first_name" db:"first_name"`
LastName string `json:"last_name" db:"last_name"`
Email string `json:"email" db:"email"`
}
// String is not required by pop and may be deleted
func (u User) String() string {
b, _ := json.Marshal(u)
return string(b)
}
func (u *User) ValidateNew(tx *pop.Connection) (*validate.Errors, error) {
verrs, err := u.validateCommon(tx)
verrs.Append(validate.Validate(
&validators.FuncValidator{
Fn: func() bool {
var b bool
if u.Email != "" {
b, err = tx.Where("email = ?", u.Email).Exists(u)
}
return !b
},
Field: "Email",
Message: "%s was already taken.",
},
))
return verrs, err
}
func (u *User) ValidateUpdate(tx *pop.Connection) (*validate.Errors, error) {
verrs, err := u.validateCommon(tx)
verrs.Append(validate.Validate(
&validators.FuncValidator{
Fn: func() bool {
var b bool
if u.Email != "" {
b, err = tx.Where("email = ? and id != ?", u.Email, u.ID).Exists(u)
}
return !b
},
Field: "Email",
Message: "%s was already taken.",
},
))
return verrs, err
}
func (u *User) validateCommon(tx *pop.Connection) (*validate.Errors, error) {
verrs := validate.Validate(
&validators.StringIsPresent{Name: "First Name", Field: u.FirstName},
&validators.StringIsPresent{Name: "Last Name", Field: u.LastName},
&validators.StringIsPresent{Name: "Email", Field: u.Email},
)
return verrs, nil
}
// Users is not required by pop and may be deleted
type Users []User
// String is not required by pop and may be deleted
func (u Users) String() string {
b, _ := json.Marshal(u)
return string(b)
}