Skip to content

Commit 5a36e83

Browse files
committed
use function instead of method to get posts
1 parent 1928ccd commit 5a36e83

File tree

6 files changed

+79
-59
lines changed

6 files changed

+79
-59
lines changed

Makefile

+5
Original file line numberDiff line numberDiff line change
@@ -25,3 +25,8 @@ check:
2525
build: GOFLAGS += -i -o dingo
2626
build:
2727
$(GO) build -v $(GOFLAGS) main.go
28+
29+
.PHONY: run
30+
run: GOFLAGS += -race
31+
run:
32+
$(GO) run -v $(GOFLAGS) main.go

app/handler/post.go

+46-28
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import (
1212

1313
func registerPostHandlers(app *golf.Application, routes map[string]map[string]interface{}) {
1414
adminChain := golf.NewChain(JWTAuthMiddleware)
15-
app.Get("/api/posts", APIPostsHandler)
15+
app.Get("/api/posts", APIPostsHandler(0, 10))
1616
routes["GET"]["posts_url"] = "/api/posts"
1717

1818
app.Get("/api/posts/:post_id", APIPostHandler)
@@ -91,34 +91,52 @@ func APIPostSlugHandler(ctx *golf.Context) {
9191
ctx.JSON(NewAPISuccessResponse(post))
9292
}
9393

94-
// APIPostsHandler gets every page, ordered by publication date.
95-
func APIPostsHandler(ctx *golf.Context) {
96-
posts := new(model.Posts)
97-
switch limitPublixhed := ctx.Param("published") {
98-
case "true":
99-
pubPosts := posts.GetAllPostList(false, true, "published_at DESC")
100-
posts.AppendPosts(pubPosts)
101-
case "false":
102-
unpubPosts := posts.GetAllPostList(false, false, "created_at DESC")
103-
posts.AppendPosts(unpubPosts)
104-
default:
105-
pubPosts := posts.GetAllPostList(false, true, "published_at DESC")
106-
posts.AppendPosts(pubPosts)
107-
unpubPosts := posts.GetAllPostList(false, false, "created_at DESC")
108-
posts.AppendPosts(unpubPosts)
109-
}
110-
ctx.JSON(NewAPISuccessResponse(posts))
111-
limitPublished, convErr := strconv.ParseBool(limitPublished)
112-
if convErr != nil {
113-
handleErr(ctx, 500, convErr)
114-
return
115-
}
116-
err := posts.GetAllPostList(false, true, "published_at DESC")
117-
if err != nil {
118-
handleErr(ctx, 404, err)
119-
return
94+
// APIPostsHandler gets an array of posts of length <= limit, starting at offset.
95+
// To paginate through posts, increment offset by limit until the length of the
96+
// post array in the response is less than limit.
97+
func APIPostsHandler(offset, limit int) golf.HandlerFunc {
98+
// offset, limit args are default values
99+
return func(ctx *golf.Context) {
100+
var posts []*model.Post
101+
var err error
102+
err = ctx.Request.ParseForm()
103+
if err != nil {
104+
ctx.SendStatus(http.StatusInternalServerError)
105+
ctx.JSON(APIResponseBodyJSON{Status: NewErrorStatusJSON(err.Error())})
106+
return
107+
}
108+
if q, _ := ctx.Query("offset"); q != "" {
109+
offset, err = strconv.Atoi(q)
110+
}
111+
if err != nil {
112+
ctx.SendStatus(http.StatusBadRequest)
113+
ctx.JSON(APIResponseBodyJSON{Status: NewErrorStatusJSON(err.Error())})
114+
return
115+
}
116+
if q, _ := ctx.Query("limit"); q != "" {
117+
limit, err = strconv.Atoi(q)
118+
}
119+
if err != nil {
120+
ctx.SendStatus(http.StatusBadRequest)
121+
ctx.JSON(APIResponseBodyJSON{Status: NewErrorStatusJSON(err.Error())})
122+
return
123+
}
124+
published, _ := ctx.Query("published")
125+
switch published {
126+
case "true":
127+
posts, err = model.GetPublishedPosts(offset, limit)
128+
case "false":
129+
posts, err = model.GetUnpublishedPosts(offset, limit)
130+
default:
131+
posts, err = model.GetAllPosts(offset, limit)
132+
}
133+
if err != nil {
134+
ctx.SendStatus(http.StatusInternalServerError)
135+
ctx.JSON(APIResponseBodyJSON{Status: NewErrorStatusJSON(err.Error())})
136+
return
137+
}
138+
ctx.JSON(NewAPISuccessResponse(posts))
120139
}
121-
ctx.JSON(NewAPISuccessResponse(posts))
122140
}
123141

124142
// APIPostCommentsHandler gets the comments on the given post.

app/model/comment.go

-1
Original file line numberDiff line numberDiff line change
@@ -168,7 +168,6 @@ func buildCommentTree(p *Comment, c *Comment, level int) {
168168
func DeleteComment(id int64) error {
169169
writeDB, err := db.Begin()
170170
if err != nil {
171-
writeDB
172171
writeDB.Rollback()
173172
return err
174173
}

app/model/post.go

+26
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ const stmtGetPostBySlug = `SELECT * FROM posts WHERE slug = ?`
1919
const stmtGetPostsByTag = `SELECT * FROM posts WHERE %s id IN ( SELECT post_id FROM posts_tags WHERE tag_id = ? ) ORDER BY published_at DESC LIMIT ? OFFSET ?`
2020
const stmtGetAllPostsByTag = `SELECT * FROM posts WHERE id IN ( SELECT post_id FROM posts_tags WHERE tag_id = ?) ORDER BY published_at DESC `
2121
const stmtGetPostsCountByTag = "SELECT count(*) FROM posts, posts_tags WHERE posts_tags.post_id = posts.id AND posts.published AND posts_tags.tag_id = ?"
22+
const stmtGetPostsOffsetLimit = `SELECT * FROM posts WHERE published = ? LIMIT ?, ?`
2223
const stmtInsertPostTag = `INSERT INTO posts_tags (id, post_id, tag_id) VALUES (?, ?, ?)`
2324
const stmtDeletePostTagsByPostId = `DELETE FROM posts_tags WHERE post_id = ?`
2425
const stmtNumberOfPosts = "SELECT count(*) FROM posts WHERE %s"
@@ -422,3 +423,28 @@ func getSafeOrderByStmt(orderBy string) string {
422423
}
423424
return "published_at DESC"
424425
}
426+
427+
func GetPublishedPosts(offset, limit int) (Posts, error) {
428+
var posts Posts
429+
err := meddler.QueryAll(db, &posts, stmtGetPostsOffsetLimit, 1, offset, limit)
430+
return posts, err
431+
}
432+
433+
func GetUnpublishedPosts(offset, limit int) (Posts, error) {
434+
var posts Posts
435+
err := meddler.QueryAll(db, &posts, stmtGetPostsOffsetLimit, 0, offset, limit)
436+
return posts, err
437+
}
438+
439+
func GetAllPosts(offset, limit int) ([]*Post, error) {
440+
pubPosts, err := GetPublishedPosts(offset, limit)
441+
if err != nil {
442+
return nil, err
443+
}
444+
unpubPosts, err := GetUnpublishedPosts(offset, limit)
445+
if err != nil {
446+
return nil, err
447+
}
448+
posts := append(pubPosts, unpubPosts...)
449+
return posts, nil
450+
}

app/model/post_test.go

+2-10
Original file line numberDiff line numberDiff line change
@@ -155,17 +155,9 @@ func TestPost(t *testing.T) {
155155
So(err, ShouldBeNil)
156156
})
157157

158-
Convey("Get all published posts list", func() {
158+
Convey("Get all posts list", func() {
159159
posts := new(Posts)
160-
err := posts.GetAllPostList(false, true, "created_at")
161-
162-
So(posts, ShouldHaveLength, 1)
163-
So(err, ShouldBeNil)
164-
})
165-
166-
Convey("Get all unpublished posts list", func() {
167-
posts := new(Posts)
168-
err := posts.GetAllPostList(false, true, "created_at")
160+
err := posts.GetAllPostList(false, false, "created_at")
169161

170162
So(posts, ShouldHaveLength, 1)
171163
So(err, ShouldBeNil)

app/utils/errors.go

-20
This file was deleted.

0 commit comments

Comments
 (0)