forked from gobuffalo/buffalo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
users.go
115 lines (99 loc) · 2.41 KB
/
users.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package actions
import (
"github.com/gobuffalo/buffalo"
"github.com/gobuffalo/buffalo/examples/json-resource/models"
"github.com/gobuffalo/buffalo/render"
"github.com/markbates/pop"
"github.com/pkg/errors"
)
// UsersResource allows CRUD with HTTP against the User model
type UsersResource struct {
buffalo.BaseResource
}
func findUserMW(h buffalo.Handler) buffalo.Handler {
return func(c buffalo.Context) error {
id, err := c.ParamInt("user_id")
if err == nil {
u := &models.User{}
tx := c.Get("tx").(*pop.Connection)
err = tx.Find(u, id)
if err != nil {
return c.Error(404, errors.WithStack(err))
}
c.Set("user", u)
}
return h(c)
}
}
// List renders all users
func (ur *UsersResource) List(c buffalo.Context) error {
users := &models.Users{}
tx := c.Get("tx").(*pop.Connection)
err := tx.All(users)
if err != nil {
return c.Error(404, errors.WithStack(err))
}
return c.Render(200, render.JSON(users))
}
// Show renders a target user
func (ur *UsersResource) Show(c buffalo.Context) error {
return c.Render(200, render.JSON(c.Get("user")))
}
// Create a user
func (ur *UsersResource) Create(c buffalo.Context) error {
u := &models.User{}
err := c.Bind(u)
if err != nil {
return errors.WithStack(err)
}
tx := c.Get("tx").(*pop.Connection)
verrs, err := u.ValidateNew(tx)
if err != nil {
return errors.WithStack(err)
}
if verrs.HasAny() {
c.Set("verrs", verrs.Errors)
return c.Render(422, render.JSON(verrs))
}
err = tx.Create(u)
if err != nil {
return errors.WithStack(err)
}
return c.Render(201, render.JSON(u))
}
// Update a target user
func (ur *UsersResource) Update(c buffalo.Context) error {
tx := c.Get("tx").(*pop.Connection)
u := c.Get("user").(*models.User)
err := c.Bind(u)
if err != nil {
return errors.WithStack(err)
}
verrs, err := u.ValidateUpdate(tx)
if err != nil {
return errors.WithStack(err)
}
if verrs.HasAny() {
c.Set("verrs", verrs.Errors)
return c.Render(422, render.JSON(verrs))
}
err = tx.Update(u)
if err != nil {
return errors.WithStack(err)
}
err = tx.Reload(u)
if err != nil {
return errors.WithStack(err)
}
return c.Render(200, render.JSON(u))
}
// Destroy removes a target user
func (ur *UsersResource) Destroy(c buffalo.Context) error {
tx := c.Get("tx").(*pop.Connection)
u := c.Get("user").(*models.User)
err := tx.Destroy(u)
if err != nil {
return errors.WithStack(err)
}
return c.Render(200, render.JSON(u))
}