Skip to content

Commit

Permalink
✨ add filter for posts
Browse files Browse the repository at this point in the history
  • Loading branch information
codermuss committed Jul 28, 2024
1 parent f2e75bb commit 165192b
Show file tree
Hide file tree
Showing 5 changed files with 101 additions and 4 deletions.
27 changes: 23 additions & 4 deletions api/post.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,11 @@ func (server *Server) CreatePost(ctx *gin.Context) {
})
}

type filteredPostsRequest struct {
Categories []int32 `json:"categories"`
Tags []int32 `json:"tags"`
}

func (server *Server) GetPosts(ctx *gin.Context) {
localeValue := ctx.Query(util.Locale)
pageStr := ctx.Query(util.Page)
Expand Down Expand Up @@ -146,13 +151,27 @@ func (server *Server) GetPosts(ctx *gin.Context) {
}

}
var req filteredPostsRequest
err := ctx.ShouldBindJSON(&req)
if err != nil {
BuildResponse(ctx, BaseResponse{
Code: http.StatusBadRequest,
Message: ResponseMessage{
Type: ERROR,
Content: err.Error(),
},
})
return
}

arg := db.GetPostsParams{
Limit: int32(size),
Offset: int32((page - 1) * size),
arg := db.GetPostsWithFilterParams{
Column3: req.Categories,
Column4: req.Tags,
Limit: int32(size),
Offset: int32((page - 1) * size),
}

blogs, err := server.store.GetPosts(ctx, arg)
blogs, err := server.store.GetPostsWithFilter(ctx, arg)
if err != nil {
BuildResponse(ctx, BaseResponse{
Code: http.StatusInternalServerError,
Expand Down
15 changes: 15 additions & 0 deletions db/mock/store.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 10 additions & 0 deletions db/query/posts.sql
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,16 @@ SELECT id, user_id, title, content, cover_image, created_at, updated_at, likes
FROM posts
ORDER BY id LIMIT $1 OFFSET $2;

-- name: GetPostsWithFilter :many
SELECT DISTINCT p.id, p.user_id, p.title, p.content, p.cover_image, p.created_at, p.updated_at, p.likes
FROM posts p
LEFT JOIN post_categories pc ON p.id = pc.post_id
LEFT JOIN post_tags pt ON p.id = pt.post_id
WHERE
(array_length($3::integer[], 1) IS NULL OR pc.category_id = ANY($3)) AND
(array_length($4::integer[], 1) IS NULL OR pt.tag_id = ANY($4))
ORDER BY p.id LIMIT $1 OFFSET $2;

-- name: UpdatePost :one
UPDATE posts
SET
Expand Down
52 changes: 52 additions & 0 deletions db/sqlc/posts.sql.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions db/sqlc/querier.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 165192b

Please sign in to comment.