From 6bfa7eb5550ddc316eeaf54f9b2b814227ca92f8 Mon Sep 17 00:00:00 2001 From: Roshan Piyush Date: Tue, 9 Jan 2024 16:24:41 +0530 Subject: [PATCH] Add pagination support for posts (#226) --- .../api/controllers/post_controller.go | 27 +++++++++++++++++-- services/community/api/models/post.go | 5 ++-- 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/services/community/api/controllers/post_controller.go b/services/community/api/controllers/post_controller.go index 646092b3..2372f2e5 100644 --- a/services/community/api/controllers/post_controller.go +++ b/services/community/api/controllers/post_controller.go @@ -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, @@ -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 diff --git a/services/community/api/models/post.go b/services/community/api/models/post.go index bd324cce..3d81537e 100644 --- a/services/community/api/models/post.go +++ b/services/community/api/models/post.go @@ -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 {