limited support for sort param

This commit is contained in:
Umputun
2017-12-25 16:58:12 -06:00
parent 05f5c435fd
commit e5c2af6d72
2 changed files with 22 additions and 3 deletions
+2 -2
View File
@@ -159,12 +159,12 @@ func (s *Server) deleteCommentCtrl(w http.ResponseWriter, r *http.Request) {
render.JSON(w, r, JSON{"id": id, "url": url})
}
// GET /find?url=post-url
// GET /find?url=post-url&sort=-time
func (s *Server) findCommentsCtrl(w http.ResponseWriter, r *http.Request) {
url := r.URL.Query().Get("url")
log.Printf("[DEBUG] get comments for %s", url)
comments, err := s.Store.Find(store.Request{Locator: store.Locator{URL: url}})
comments, err := s.Store.Find(store.Request{Locator: store.Locator{URL: url}, Sort: r.URL.Query().Get("sort")})
if err != nil {
log.Printf("[WARN] can't get comments for %s, %s", url, err)
httpError(w, r, http.StatusInternalServerError, err, "can't load comments comment")
+20 -1
View File
@@ -135,7 +135,26 @@ func (b *BoltDB) Find(request Request) ([]Comment, error) {
})
})
sort.Slice(res, func(i, j int) bool { return res[i].Timestamp.Before(res[j].Timestamp) })
// sort result according to request.Sort
sort.Slice(res, func(i, j int) bool {
switch request.Sort {
case "+time", "-time", "time":
if strings.HasPrefix(request.Sort, "-") {
return res[i].Timestamp.After(res[j].Timestamp)
}
return res[i].Timestamp.Before(res[j].Timestamp)
case "+score", "-score", "score":
if strings.HasPrefix(request.Sort, "-") {
return res[i].Score > res[j].Score
}
return res[i].Score < res[j].Score
default:
return res[i].Timestamp.Before(res[j].Timestamp)
}
})
return res, err
}