Clean verbose or not and optional one query param

master
Bel LaPointe 2020-07-22 23:43:21 -06:00
parent 098a2b9bbc
commit cc7ea37676
1 changed files with 47 additions and 23 deletions

View File

@ -1,6 +1,7 @@
package view package view
import ( import (
"context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"local/dndex/config" "local/dndex/config"
@ -45,21 +46,44 @@ func who(g storage.Graph, w http.ResponseWriter, r *http.Request) error {
namespace = strings.Replace(namespace[1:], "/", ".", -1) namespace = strings.Replace(namespace[1:], "/", ".", -1)
ids := r.URL.Query()["id"] ids := r.URL.Query()["id"]
_, verbose := r.URL.Query()["v"] _, verbose := r.URL.Query()["v"]
_, one := r.URL.Query()["one"]
results := make(map[string]entity.One) results := make(map[string]entity.One)
for i := 0; i < len(ids); i++ { for i := 0; i < len(ids); i++ {
id := ids[i] id := ids[i]
ones, err := g.List(r.Context(), namespace, id) one, err := whoOne(r.Context(), g, namespace, id, verbose)
if err != nil { if err != nil {
return err return err
} }
results[id] = one
}
var marshalme interface{}
if one {
for k := range results {
marshalme = results[k]
break
}
} else {
marshalme = results
}
log.Printf("id=%+v, one=%v, verbose=%v, results:%+v", ids, one, verbose, marshalme)
enc := json.NewEncoder(w)
enc.SetIndent("", " ")
return enc.Encode(marshalme)
}
func whoOne(ctx context.Context, g storage.Graph, namespace, id string, verbose bool) (entity.One, error) {
ones, err := g.List(ctx, namespace, id)
if err != nil {
return entity.One{}, err
}
if len(ones) != 1 { if len(ones) != 1 {
ones = append(ones, entity.One{}) ones = append(ones, entity.One{})
} }
one := ones[0] one := ones[0]
if verbose { if verbose {
ones, err := g.List(r.Context(), namespace, one.Peers()...) ones, err := g.List(ctx, namespace, one.Peers()...)
if err != nil { if err != nil {
return err return entity.One{}, err
} }
for _, another := range ones { for _, another := range ones {
another.Connections = nil another.Connections = nil
@ -73,11 +97,11 @@ func who(g storage.Graph, w http.ResponseWriter, r *http.Request) error {
} }
} }
} }
} else {
for j, v := range one.Connections {
v.Name = ""
one.Connections[j] = v
} }
results[id] = one
} }
log.Println("results:", results) return one, nil
enc := json.NewEncoder(w)
enc.SetIndent("", " ")
return enc.Encode(results)
} }