@@ -2,6 +2,7 @@ package rest
22
33import (
44 "context"
5+ "encoding/json"
56 "fmt"
67 "github.com/dgrijalva/jwt-go"
78 "github.com/labstack/echo/v4"
@@ -12,15 +13,17 @@ import (
1213 "go.mongodb.org/mongo-driver/bson/primitive"
1314 "go.mongodb.org/mongo-driver/mongo"
1415 "go.mongodb.org/mongo-driver/mongo/options"
15- "io/ioutil"
16- "k8s.io/apimachinery/pkg/util/json"
16+ "math"
1717 "net/http"
18+ "strconv"
19+ "strings"
1820 "time"
1921)
2022
2123var (
2224 client = connectMongo ()
2325 collection = client .Database (util .GetEnv ("MONGODB_DATABASE" )).Collection ("posts" )
26+ httpClient = & http.Client {Timeout : 2 * time .Second }
2427)
2528
2629func connectMongo () * mongo.Client {
@@ -129,48 +132,83 @@ func CreateDefaultPosts() {
129132 }
130133}
131134
132- func GetTasksApi (c echo.Context ) []model.Task {
135+ func GetTasksApi (c echo.Context , id string ) []model.TaskDto {
133136 authorizationHeader := c .Request ().Header .Get ("Authorization" )
134137
135- req , err := http .NewRequest ("GET" , util .GetEnv ("TASKS_API_URL" ), nil )
138+ req , err := http .NewRequest ("GET" , util .GetEnv ("TASKS_API_URL" )+ "?postId=" + id , nil )
136139 req .Header .Add ("Authorization" , authorizationHeader )
137140
138- client := & http.Client {}
139- resp , err := client .Do (req )
141+ resp , err := httpClient .Do (req )
140142 if err != nil {
141143 log .Warn (fmt .Sprintf ("Error Task Api Connection = %v" , err ))
142144 return nil
143145 }
144146 defer resp .Body .Close ()
145- body , err := ioutil .ReadAll (resp .Body )
147+ var taskDto model.PageTaskDto
148+ err = json .NewDecoder (resp .Body ).Decode (& taskDto )
146149 if err != nil {
147150 log .Warn (fmt .Sprintf ("Error Read Task Api = %v" , err ))
148151 return nil
149152 }
150- var tasks []model.Task
151- if err := json .Unmarshal (body , & tasks ); err != nil {
152- log .Warn (fmt .Sprintf ("Error Parse Task Api Response = %v" , err ))
153- return nil
154- }
155-
156- return tasks
153+ return taskDto .Task
157154}
158155
159156func GetAllPosts (c echo.Context ) error {
157+ page := 0
158+ size := 10
159+ if c := c .QueryParam ("page" ); c != "" {
160+ page , _ = strconv .Atoi (c )
161+ }
162+ if c := c .QueryParam ("size" ); c != "" {
163+ size , _ = strconv .Atoi (c )
164+ }
165+ var searchByText string
166+ if strings .Contains (c .QueryString (), "&" ) {
167+ searchByText = c .QueryString ()
168+ searchByText = searchByText [0 :strings .Index (searchByText , "&" )]
169+ }
170+ log .Info (fmt .Sprintf ("QueryString = %v" , searchByText ))
171+ pageInt64 := int64 (page )
172+ sizeInt64 := int64 (size )
160173 ctx := context .TODO ()
161- var posts []* model.Post
174+ pagination := new (model.Pagination )
175+ pagination .Page = pageInt64
176+ pagination .Size = sizeInt64
177+ var posts []model.PostDto
162178 var cur * mongo.Cursor
163- opts := options .Find ().SetSort (bson.D {{"createdDate" , 1 }})
179+ opts := options .Find ().SetSort (bson.D {{"createdDate" , 1 }}). SetSkip ( pageInt64 ). SetLimit ( sizeInt64 )
164180
165181 if isAdmin (c ) {
166- cursor , err := collection .Find (ctx , bson.D {}, opts )
182+ filter := bson.M {}
183+ if searchByText != "" {
184+ filter = bson.M {
185+ "name" : bson.D {{"$all" , bson.A {searchByText }}},
186+ }
187+ }
188+ count , err2 := collection .CountDocuments (ctx , filter )
189+ if err2 != nil {
190+ return err2
191+ }
192+ pagination .TotalElements = count
193+ cursor , err := collection .Find (ctx , filter , opts )
167194 if err != nil {
168195 return err
169196 }
170197 cur = cursor
171198 } else {
172199 createdByUser := getAuthUser (c )["sub" ].(string )
173200 filter := bson.M {"createdByUser" : createdByUser }
201+ if searchByText != "" {
202+ filter = bson.M {
203+ "createdByUser" : createdByUser ,
204+ "name" : bson.D {{"$all" , bson.A {searchByText }}},
205+ }
206+ }
207+ count , err2 := collection .CountDocuments (ctx , filter )
208+ if err2 != nil {
209+ return err2
210+ }
211+ pagination .TotalElements = count
174212
175213 cursor , err := collection .Find (ctx , filter , opts )
176214
@@ -185,12 +223,36 @@ func GetAllPosts(c echo.Context) error {
185223 if err := cur .Decode (& post ); err != nil {
186224 return err
187225 }
226+ if post .LastModifiedDate != nil && post .LastModifiedDate .IsZero () {
227+ post .LastModifiedDate = nil
228+ }
229+ postDto := model.PostDto {
230+ ID : post .ID .Hex (),
231+ Name : post .Name ,
232+ CreatedDate : post .CreatedDate .String (),
233+ CreatedByUser : post .CreatedByUser ,
234+ LastModifiedByUser : post .LastModifiedByUser ,
235+ }
188236 if util .GetEnvAsBool ("CALL_TASK_API" ) {
189- post .Tasks = GetTasksApi (c )
237+ postDto .Tasks = GetTasksApi (c , postDto . ID )
190238 }
191- posts = append (posts , & post )
239+ if post .LastModifiedDate != nil && ! post .LastModifiedDate .IsZero () {
240+ postDto .LastModifiedDate = post .LastModifiedDate .String ()
241+ }
242+ posts = append (posts , postDto )
243+ }
244+ pagination .Post = append (posts )
245+ if pagination .Post == nil {
246+ pagination .Post = []model.PostDto {}
192247 }
193- return c .JSON (http .StatusOK , posts )
248+
249+ if pagination .TotalPages > sizeInt64 {
250+ pagination .TotalPages = int64 (math .Ceil (float64 (pagination .TotalElements / sizeInt64 )))
251+ } else {
252+ pagination .TotalPages = 1
253+ }
254+
255+ return c .JSON (http .StatusOK , pagination )
194256}
195257
196258func CreatePost (c echo.Context ) error {
@@ -211,7 +273,7 @@ func CreatePost(c echo.Context) error {
211273 return c .JSON (http .StatusCreated , u )
212274}
213275
214- func GetPost (c echo.Context ) error {
276+ func GetPostById (c echo.Context ) error {
215277 id := c .Param ("id" )
216278 if "" == id {
217279 panic ("Id is mandatory!" )
@@ -254,17 +316,22 @@ func UpdatePost(c echo.Context) error {
254316 return echo .NewHTTPError (http .StatusNotFound , fmt .Sprintf ("Not found ID: %v" , id ))
255317 }
256318
257- u := new (model.Post )
319+ u := new (model.PostDto )
258320 if err := c .Bind (u ); err != nil {
259321 return err
260322 }
261323 if err := c .Validate (u ); err != nil {
262324 return err
263325 }
264326
265- u .LastModifiedDate = time .Now ()
266- u .LastModifiedByUser = getAuthUser (c )["sub" ].(string )
267- if _ , err := collection .UpdateOne (ctx , filter , u ); err != nil {
327+ var t = time .Now ()
328+ post .Name = u .Name
329+ post .LastModifiedDate = & t
330+ post .LastModifiedByUser = getAuthUser (c )["sub" ].(string )
331+ update := bson.M {
332+ "$set" : post ,
333+ }
334+ if _ , err := collection .UpdateOne (ctx , filter , update ); err != nil {
268335 return err
269336 }
270337 return c .JSON (http .StatusOK , u )
0 commit comments