github.com/jasonish/buffalo@v0.8.2-0.20170413145823-bacbdd415f1b/examples/json-resource/models/user.go (about) 1 package models 2 3 import ( 4 "encoding/json" 5 "time" 6 7 "github.com/markbates/going/validate" 8 "github.com/markbates/going/validate/validators" 9 "github.com/markbates/pop" 10 ) 11 12 // User model stores information about a user account 13 type User struct { 14 ID int `json:"id" db:"id"` 15 CreatedAt time.Time `json:"created_at" db:"created_at"` 16 UpdatedAt time.Time `json:"updated_at" db:"updated_at"` 17 FirstName string `json:"first_name" db:"first_name"` 18 LastName string `json:"last_name" db:"last_name"` 19 Email string `json:"email" db:"email"` 20 } 21 22 // String is not required by pop and may be deleted 23 func (u User) String() string { 24 b, _ := json.Marshal(u) 25 return string(b) 26 } 27 28 // ValidateNew validates the User fields and checks whether a user has 29 // already claimed that email address 30 func (u *User) ValidateNew(tx *pop.Connection) (*validate.Errors, error) { 31 verrs, err := u.validateCommon(tx) 32 verrs.Append(validate.Validate( 33 &validators.FuncValidator{ 34 Fn: func() bool { 35 var b bool 36 if u.Email != "" { 37 b, err = tx.Where("email = ?", u.Email).Exists(u) 38 } 39 return !b 40 }, 41 Field: "Email", 42 Message: "%s was already taken.", 43 }, 44 )) 45 return verrs, err 46 } 47 48 // ValidateUpdate validates the User fields and confirms that the email has 49 // not been claimed by a different user 50 func (u *User) ValidateUpdate(tx *pop.Connection) (*validate.Errors, error) { 51 verrs, err := u.validateCommon(tx) 52 verrs.Append(validate.Validate( 53 &validators.FuncValidator{ 54 Fn: func() bool { 55 var b bool 56 if u.Email != "" { 57 b, err = tx.Where("email = ? and id != ?", u.Email, u.ID).Exists(u) 58 } 59 return !b 60 }, 61 Field: "Email", 62 Message: "%s was already taken.", 63 }, 64 )) 65 return verrs, err 66 } 67 68 func (u *User) validateCommon(tx *pop.Connection) (*validate.Errors, error) { 69 verrs := validate.Validate( 70 &validators.StringIsPresent{Name: "First Name", Field: u.FirstName}, 71 &validators.StringIsPresent{Name: "Last Name", Field: u.LastName}, 72 &validators.StringIsPresent{Name: "Email", Field: u.Email}, 73 ) 74 return verrs, nil 75 } 76 77 // Users is not required by pop and may be deleted 78 type Users []User 79 80 // String is not required by pop and may be deleted 81 func (u Users) String() string { 82 b, _ := json.Marshal(u) 83 return string(b) 84 }