@@ -27,9 +27,22 @@ func NewPostService(postRepo repo.PostRepository, userRepo repo.UserRepository)
2727 }
2828}
2929
30- // GetPosts retrieves all posts.
31- func (s * PostService ) GetPosts (ctx context.Context ) (httpResponse gmodel.HTTPResponse , httpStatusCode int ) {
32- posts , err := s .postRepo .GetPosts (ctx )
30+ // GetPosts retrieves a paginated list of posts.
31+ func (s * PostService ) GetPosts (ctx context.Context , page , pageSize int ) (httpResponse gmodel.HTTPResponse , httpStatusCode int ) {
32+ // normalize pagination params
33+ if page <= 0 {
34+ page = 1
35+ }
36+ if pageSize <= 0 {
37+ pageSize = 10
38+ }
39+ if pageSize > 100 {
40+ pageSize = 100
41+ }
42+ offset := (page - 1 ) * pageSize
43+
44+ // get total count
45+ total , err := s .postRepo .CountPosts (ctx )
3346 if err != nil {
3447 if errors .Is (err , context .Canceled ) {
3548 httpResponse .Message = "request canceled"
@@ -43,13 +56,46 @@ func (s *PostService) GetPosts(ctx context.Context) (httpResponse gmodel.HTTPRes
4356 return
4457 }
4558
59+ if total == 0 {
60+ httpResponse .Message = "no post found"
61+ httpStatusCode = http .StatusNotFound
62+ return
63+ }
64+
65+ // get paginated posts
66+ posts , err := s .postRepo .ListPosts (ctx , pageSize , offset )
67+ if err != nil {
68+ if errors .Is (err , context .Canceled ) {
69+ httpResponse .Message = "request canceled"
70+ httpStatusCode = http .StatusRequestTimeout
71+ return
72+ }
73+
74+ log .WithError (err ).Error ("GetPosts.s.2" )
75+ httpResponse .Message = "internal server error"
76+ httpStatusCode = http .StatusInternalServerError
77+ return
78+ }
79+
4680 if len (posts ) == 0 {
4781 httpResponse .Message = "no post found"
4882 httpStatusCode = http .StatusNotFound
4983 return
5084 }
5185
52- httpResponse .Message = posts
86+ hasNext := int64 (page * pageSize ) < total
87+ hasPrevious := page > 1
88+
89+ result := map [string ]any {
90+ "hasNext" : hasNext ,
91+ "hasPrevious" : hasPrevious ,
92+ "page" : page ,
93+ "pageSize" : pageSize ,
94+ "posts" : posts ,
95+ "total" : total ,
96+ }
97+
98+ httpResponse .Message = result
5399 httpStatusCode = http .StatusOK
54100 return
55101}
0 commit comments