-
Notifications
You must be signed in to change notification settings - Fork 0
/
update.go
82 lines (66 loc) · 1.88 KB
/
update.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
package user
import (
"github.com/pkg/errors"
"github.com/dzeban/conduit/app"
"github.com/dzeban/conduit/password"
)
type UpdateRequest struct {
User UpdateUser `json:"user"`
}
type UpdateUser struct {
Name string `json:"username,omitempty"`
Email string `json:"email,omitempty"`
Password string `json:"password,omitempty"` // NOTE: Plaintext password from user
Bio string `json:"bio,omitempty"`
Image string `json:"image,omitempty"`
}
func (r *UpdateRequest) Validate() error {
if r.User.Name == "" &&
r.User.Email == "" &&
r.User.Bio == "" &&
r.User.Image == "" &&
r.User.Password == "" {
return errors.New("at least one of username, email, bio, image, password is required for update")
}
return nil
}
// Update modifies user found by id with the new data passed in user.
// It returns updated user.
func (s *Service) Update(id int, req *UpdateRequest) (*app.User, error) {
// Validate request
err := req.Validate()
if err != nil {
return nil, app.ServiceError(err)
}
// Check user exists
u, err := s.store.GetUserById(id)
if err != nil {
return nil, app.InternalError(errors.Wrap(err, "failed to get user for update"))
}
if u == nil {
return nil, app.ServiceError(errorUserNotFound)
}
// Set fields to update
u.Name = req.User.Name
u.Email = req.User.Email
u.Bio = req.User.Bio
u.Image = req.User.Image
// If password is being changed, make the hash from it
if req.User.Password != "" {
hash, err := password.HashAndEncode(req.User.Password)
if err != nil {
return nil, app.InternalError(errors.Wrap(err, "failed to create password hsah"))
}
u.PasswordHash = hash
}
err = s.store.UpdateUser(u)
if err != nil {
return nil, app.InternalError(errors.Wrap(err, "failed to update user"))
}
// Return updated user
u, err = s.store.GetUserById(id)
if err != nil {
return nil, app.InternalError(errorUserNotFound)
}
return u, nil
}