/
descendants_faceted.go
86 lines (63 loc) · 2.05 KB
/
descendants_faceted.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package api
import (
"encoding/json"
"log/slog"
"net/http"
// TBD...
// "github.com/sfomuseum/go-http-auth"
"github.com/whosonfirst/go-whosonfirst-spelunker"
"github.com/whosonfirst/go-whosonfirst-spelunker-httpd"
)
type DescendantsFacetedHandlerOptions struct {
Spelunker spelunker.Spelunker
// TBD...
// Authenticator auth.Authenticator
}
func DescendantsFacetedHandler(opts *DescendantsFacetedHandlerOptions) (http.Handler, error) {
fn := func(rsp http.ResponseWriter, req *http.Request) {
ctx := req.Context()
logger := slog.Default()
logger = logger.With("request", req.URL)
uri, err, status := httpd.ParseURIFromRequest(req, nil)
if err != nil {
logger.Error("Failed to parse URI from request", "error", err)
http.Error(rsp, spelunker.ErrNotFound.Error(), status)
return
}
logger = logger.With("wofid", uri.Id)
filter_params := httpd.DefaultFilterParams()
filters, err := httpd.FiltersFromRequest(ctx, req, filter_params)
if err != nil {
logger.Error("Failed to derive filters from request", "error", err)
http.Error(rsp, "Bad request", http.StatusBadRequest)
return
}
facets, err := httpd.FacetsFromRequest(ctx, req, filter_params)
if err != nil {
logger.Error("Failed to derive facets from requrst", "error", err)
http.Error(rsp, "Bad request", http.StatusBadRequest)
return
}
if len(facets) == 0 {
logger.Error("No facets from requrst")
http.Error(rsp, "Bad request", http.StatusBadRequest)
return
}
facets_rsp, err := opts.Spelunker.GetDescendantsFaceted(ctx, uri.Id, filters, facets)
if err != nil {
logger.Error("Failed to get facets for descendants", "error", err)
http.Error(rsp, "Internal server error", http.StatusInternalServerError)
return
}
rsp.Header().Set("Content-Type", "application/json")
enc := json.NewEncoder(rsp)
err = enc.Encode(facets_rsp)
if err != nil {
logger.Error("Failed to encode facets response", "error", err)
http.Error(rsp, "womp womp", http.StatusInternalServerError)
return
}
}
h := http.HandlerFunc(fn)
return h, nil
}