-
Notifications
You must be signed in to change notification settings - Fork 1
/
post.go
116 lines (97 loc) · 2.62 KB
/
post.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
116
package admin
import (
"errors"
"net/http"
"time"
"github.com/alexedwards/flow"
"github.com/google/uuid"
"github.com/theandrew168/bloggulus/backend/domain/admin"
"github.com/theandrew168/bloggulus/backend/postgres"
"github.com/theandrew168/bloggulus/backend/web/api/util"
"github.com/theandrew168/bloggulus/backend/web/api/validator"
)
type jsonPost struct {
ID uuid.UUID `json:"id"`
BlogID uuid.UUID `json:"blogID"`
URL string `json:"url"`
Title string `json:"title"`
PublishedAt time.Time `json:"publishedAt"`
}
func marshalPost(post *admin.Post) jsonPost {
p := jsonPost{
ID: post.ID(),
BlogID: post.BlogID(),
URL: post.URL(),
Title: post.Title(),
PublishedAt: post.PublishedAt(),
}
return p
}
func (app *Application) handlePostRead() http.HandlerFunc {
type response struct {
Post jsonPost `json:"post"`
}
return func(w http.ResponseWriter, r *http.Request) {
v := validator.New()
id, err := uuid.Parse(flow.Param(r.Context(), "id"))
if err != nil {
v.AddError("id", "must be a valid UUID")
util.BadRequestResponse(w, r, v.Errors)
return
}
post, err := app.store.Admin().Post().Read(id)
if err != nil {
if errors.Is(err, postgres.ErrNotFound) {
util.NotFoundResponse(w, r)
return
}
util.ServerErrorResponse(w, r, err)
return
}
resp := response{
Post: marshalPost(post),
}
err = util.WriteJSON(w, 200, resp, nil)
if err != nil {
util.ServerErrorResponse(w, r, err)
return
}
}
}
func (app *Application) handlePostList() http.HandlerFunc {
type response struct {
Posts []jsonPost `json:"posts"`
}
return func(w http.ResponseWriter, r *http.Request) {
v := validator.New()
qs := r.URL.Query()
// check pagination params
page := util.ReadInt(qs, "page", 1, v)
v.Check(page >= 1, "page", "must be greater than or equal to 1")
size := util.ReadInt(qs, "size", 20, v)
v.Check(size >= 1, "size", "must be greater than or equal to 1")
v.Check(size <= 50, "size", "must be less than or equal to 50")
if !v.Valid() {
util.BadRequestResponse(w, r, v.Errors)
return
}
limit, offset := util.PageSizeToLimitOffset(page, size)
posts, err := app.store.Admin().Post().List(limit, offset)
if err != nil {
util.ServerErrorResponse(w, r, err)
return
}
resp := response{
// use make here to encode JSON as "[]" instead of "null" if empty
Posts: make([]jsonPost, 0),
}
for _, post := range posts {
resp.Posts = append(resp.Posts, marshalPost(post))
}
err = util.WriteJSON(w, 200, resp, nil)
if err != nil {
util.ServerErrorResponse(w, r, err)
return
}
}
}