Skip to content

Commit

Permalink
Add pagination support for posts (#226)
Browse files Browse the repository at this point in the history
  • Loading branch information
piyushroshan authored Jan 9, 2024
1 parent c3d5c02 commit 6bfa7eb
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 4 deletions.
27 changes: 25 additions & 2 deletions services/community/api/controllers/post_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,11 @@ import (
"encoding/json"
"io/ioutil"
"net/http"
"strconv"

"github.com/gorilla/mux"
"crapi.proj/goservice/api/models"
"crapi.proj/goservice/api/responses"
"github.com/gorilla/mux"
)

//AddNewPost add post in database,
Expand Down Expand Up @@ -72,8 +73,30 @@ func (s *Server) GetPostByID(w http.ResponseWriter, r *http.Request) {
//GetPost Vulnerabilities
func (s *Server) GetPost(w http.ResponseWriter, r *http.Request) {
//post := models.Post{}
limit_param := r.URL.Query().Get("limit")
limit := 30
err := error(nil)
if limit_param != "" {
// Parse limit_param and set to limit
limit, err = strconv.Atoi(limit_param)
if err != nil {
limit = 30
}
}
if limit > 50 {
limit = 50
}

page_param := r.URL.Query().Get("page")
page := 0
if page_param != "" {
page, err = strconv.Atoi(page_param)
if err != nil {
page = 0
}
}
posts, err := models.FindAllPost(s.Client, page, limit)

posts, err := models.FindAllPost(s.Client)
if err != nil {
responses.ERROR(w, http.StatusInternalServerError, err)
return
Expand Down
5 changes: 3 additions & 2 deletions services/community/api/models/post.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,12 +104,13 @@ func GetPostByID(client *mongo.Client, ID string) (Post, error) {
}

//FindAllPost return all recent post
func FindAllPost(client *mongo.Client) ([]interface{}, error) {
func FindAllPost(client *mongo.Client, page int, limit int) ([]interface{}, error) {
post := []Post{}

options := options.Find()
options.SetSort(bson.D{{"_id", -1}})
options.SetLimit(10)
options.SetLimit(int64(limit))
options.SetSkip(int64(page * limit))
collection := client.Database("crapi").Collection("post")
cur, err := collection.Find(context.Background(), bson.D{}, options)
if err != nil {
Expand Down

0 comments on commit 6bfa7eb

Please sign in to comment.