From dc5729f20c412af1019707906f9aeff0c5966bd7 Mon Sep 17 00:00:00 2001 From: Bel LaPointe Date: Fri, 24 Jul 2020 19:27:50 -0600 Subject: [PATCH] Optional sorting on TRACE --- view/who.go | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/view/who.go b/view/who.go index 5a9c5bc..886136b 100644 --- a/view/who.go +++ b/view/who.go @@ -9,6 +9,7 @@ import ( "local/dndex/storage/entity" "local/dndex/storage/operator" "net/http" + "sort" "github.com/buger/jsonparser" "go.mongodb.org/mongo-driver/bson" @@ -190,6 +191,7 @@ func whoTrace(namespace string, g storage.Graph, w http.ResponseWriter, r *http. if err != nil { return err } + ones = sortOnes(ones, r) names := make([]string, len(ones)) for i := range ones { names[i] = ones[i].Name @@ -206,3 +208,28 @@ func getID(r *http.Request) (string, error) { } return id, nil } + +func sortOnes(ones []entity.One, r *http.Request) []entity.One { + sorting := r.URL.Query().Get("sort") + if sorting == "" { + sorting = entity.Modified + } + order := r.URL.Query().Get("order") + if order == "" { + order = "-1" + } + asc := order != "-1" + sort.Slice(ones, func(i, j int) bool { + ib, _ := bson.Marshal(ones[i]) + jb, _ := bson.Marshal(ones[j]) + var im, jm bson.M + bson.Unmarshal(ib, &im) + bson.Unmarshal(jb, &jm) + iv, _ := im[sorting] + jv, _ := jm[sorting] + is := fmt.Sprint(iv) + js := fmt.Sprint(jv) + return (asc && is < js) || (!asc && is > js) + }) + return ones +}