diff --git a/relay/main.go b/relay/main.go index 9bbdc32..e6745da 100644 --- a/relay/main.go +++ b/relay/main.go @@ -1,6 +1,7 @@ package main import ( + "encoding/json" "fmt" "net/http" "os" @@ -210,6 +211,42 @@ func main() { `) }) + mux.HandleFunc("/api/stats", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + + // Query the number of events for each kind, sorted by kind + rows, err := db.DB.Query("SELECT kind, COUNT(*) FROM event GROUP BY kind ORDER BY kind") + if err != nil { + http.Error(w, fmt.Sprintf("Error querying event kinds: %v", err), http.StatusInternalServerError) + return + } + defer rows.Close() + + stats := make(map[string]int) + totalCount := 0 + for rows.Next() { + var kind string + var count int + if err := rows.Scan(&kind, &count); err != nil { + http.Error(w, fmt.Sprintf("Error scanning row: %v", err), http.StatusInternalServerError) + return + } + stats[kind] = count + totalCount += count + } + + // Add total count to the stats + response := map[string]interface{}{ + "total": totalCount, + "kinds": stats, + } + + // Encode stats to JSON and write to response + if err := json.NewEncoder(w).Encode(response); err != nil { + http.Error(w, fmt.Sprintf("Error encoding JSON: %v", err), http.StatusInternalServerError) + } + }) + fmt.Println("running on :3334") http.ListenAndServe(":3334", relay) }