Skip to content

Commit

Permalink
Merge pull request #874 from go-kivik/otherViews
Browse files Browse the repository at this point in the history
Other views
  • Loading branch information
flimzy authored Feb 4, 2024
2 parents e415338 + ca39d3d commit 49b646c
Show file tree
Hide file tree
Showing 3 changed files with 448 additions and 17 deletions.
43 changes: 39 additions & 4 deletions x/server/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,18 @@
package server

import (
"context"
"encoding/json"
"fmt"
"net/http"
"path/filepath"
"strconv"
"strings"
"time"

"github.com/go-chi/chi/v5"
"gitlab.com/flimzy/httpe"

"github.com/go-kivik/kivik/v4"
"github.com/go-kivik/kivik/v4/driver"
"github.com/go-kivik/kivik/v4/internal"
)
Expand Down Expand Up @@ -226,10 +228,26 @@ loop:
return updates.Err()
}

func (s *Server) allDocs() httpe.HandlerWithError {
// whichView returns `_all_docs`, `_local_docs`, of `_design_docs`, and whether
// the path ends with /queries.
func whichView(r *http.Request) (ddoc, view string, isQueries bool) {
parts := strings.Split(strings.Trim(r.URL.Path, "/"), "/")
var isQuery bool
if parts[len(parts)-1] == "queries" {
isQuery = true
parts = parts[:len(parts)-1]
}
if parts[1] == "_design" {
return parts[2], parts[4], isQuery
}
return "", parts[len(parts)-1], isQuery
}

func (s *Server) query() httpe.HandlerWithError {
return httpe.HandlerWithErrorFunc(func(w http.ResponseWriter, r *http.Request) error {
ddoc, view, isQueries := whichView(r)
req := map[string]interface{}{}
if _, last := filepath.Split(r.URL.Path); last == "queries" {
if isQueries {
var jsonReq struct {
Queries []map[string]interface{} `json:"queries"`
}
Expand All @@ -243,7 +261,24 @@ func (s *Server) allDocs() httpe.HandlerWithError {
}
}
db := chi.URLParam(r, "db")
rows := s.client.DB(db).AllDocs(r.Context(), options(r))
var viewFunc func(context.Context, ...kivik.Option) *kivik.ResultSet
if ddoc == "" {
switch view {
case "_all_docs":
viewFunc = s.client.DB(db).AllDocs
case "_local_docs":
viewFunc = s.client.DB(db).LocalDocs
case "_design_docs":
viewFunc = s.client.DB(db).DesignDocs
default:
return &internal.Error{Status: http.StatusNotFound, Message: fmt.Sprintf("kivik: view %q not found", view)}
}
} else {
viewFunc = func(ctx context.Context, opts ...kivik.Option) *kivik.ResultSet {
return s.client.DB(db).Query(ctx, ddoc, view, options(r))
}
}
rows := viewFunc(r.Context(), options(r))
defer rows.Close()

if err := rows.Err(); err != nil {
Expand Down
Loading

0 comments on commit 49b646c

Please sign in to comment.