Skip to content
This repository was archived by the owner on Sep 2, 2024. It is now read-only.

Commit cda58a6

Browse files
committed
feat: add new db endpoint for getting count of collection
1 parent e232ba1 commit cda58a6

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

db.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,40 @@ func (database *Database) list(w http.ResponseWriter, r *http.Request) {
136136
respond(w, http.StatusOK, result)
137137
}
138138

139+
func (database *Database) count(w http.ResponseWriter, r *http.Request) {
140+
var clauses [][]interface{}
141+
142+
if err := json.NewDecoder(r.Body).Decode(&clauses); err != nil {
143+
// Here we don't return an error because filters are optional
144+
database.log.Error().Err(err).Msg("error parsing body")
145+
}
146+
147+
filter, err := backend.DB.ParseQuery(clauses)
148+
if err != nil {
149+
// Here we don't return an error because filters are optional
150+
database.log.Error().Err(err).Msg("error parsing query")
151+
}
152+
153+
conf, auth, err := middleware.Extract(r, true)
154+
if err != nil {
155+
database.log.Error().Err(err).Msg("error extracting conf and auth")
156+
http.Error(w, err.Error(), http.StatusBadRequest)
157+
158+
return
159+
}
160+
161+
col := getURLPart(r.URL.Path, 3)
162+
163+
result, err := backend.DB.Count(auth, conf.Name, col, filter)
164+
if err != nil {
165+
http.Error(w, err.Error(), http.StatusInternalServerError)
166+
167+
return
168+
}
169+
170+
respond(w, http.StatusOK, map[string]int64{"count": result})
171+
}
172+
139173
func (database *Database) get(w http.ResponseWriter, r *http.Request) {
140174
conf, auth, err := middleware.Extract(r, true)
141175
if err != nil {

server.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,7 @@ func Start(c config.AppConfig, log *logger.Logger) {
142142

143143
// database routes
144144
http.Handle("/db/", middleware.Chain(http.HandlerFunc(database.dbreq), stdAuth...))
145+
http.Handle("/db/count/", middleware.Chain(http.HandlerFunc(database.count), stdAuth...))
145146
http.Handle("/query/", middleware.Chain(http.HandlerFunc(database.query), stdAuth...))
146147
http.Handle("/inc/", middleware.Chain(http.HandlerFunc(database.increase), stdAuth...))
147148
http.Handle("/sudoquery/", middleware.Chain(http.HandlerFunc(database.query), stdRoot...))
@@ -216,6 +217,7 @@ func Start(c config.AppConfig, log *logger.Logger) {
216217
http.Handle("/localfs/", http.StripPrefix("/localfs/", fs))
217218
}
218219

220+
// count
219221
// ui routes
220222
webUI := ui{log: log}
221223
http.HandleFunc("/ui/login", webUI.auth)

0 commit comments

Comments
 (0)