From 46c9e4af3ccfa1d5d971faaa413afc25fe857672 Mon Sep 17 00:00:00 2001 From: Chris kerr Date: Sat, 27 Jul 2024 15:59:08 -0400 Subject: [PATCH] frontend showing top 10 recent events, no formatting --- web/http.go | 71 +++++++++++++++++++++++++++++++++++++++----- web/views/index.html | 11 +++++++ 2 files changed, 74 insertions(+), 8 deletions(-) diff --git a/web/http.go b/web/http.go index fe2596e..3195be5 100644 --- a/web/http.go +++ b/web/http.go @@ -1,19 +1,38 @@ package web import ( + "context" + "grain/relay/db" + relay "grain/relay/types" "html/template" "net/http" + + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo" + "go.mongodb.org/mongo-driver/mongo/options" ) -func RootHandler(w http.ResponseWriter, r *http.Request) { - data := PageData{ - Title: "GRAIN Relay", - } - RenderTemplate(w, data, "index.html") -} type PageData struct { - Title string - Theme string + Title string + Theme string + Events []relay.Event +} + +func RootHandler(w http.ResponseWriter, r *http.Request) { + // Fetch the top ten most recent events + client := db.GetClient() + events, err := FetchTopTenRecentEvents(client) + if err != nil { + http.Error(w, "Unable to fetch events", http.StatusInternalServerError) + return + } + + data := PageData{ + Title: "GRAIN Relay", + Events: events, + } + + RenderTemplate(w, data, "index.html") } // Define the base directories for views and templates @@ -59,3 +78,39 @@ func PrependDir(dir string, files []string) []string { } return fullPaths } + +// FetchTopTenRecentEvents queries the database and returns the top ten most recent events. +func FetchTopTenRecentEvents(client *mongo.Client) ([]relay.Event, error) { + var results []relay.Event + + collections, err := client.Database("grain").ListCollectionNames(context.TODO(), bson.M{}) + if err != nil { + return nil, err + } + + for _, collectionName := range collections { + collection := client.Database("grain").Collection(collectionName) + filter := bson.D{} + opts := options.Find().SetSort(bson.D{{Key: "createdat", Value: -1}}).SetLimit(10) + + cursor, err := collection.Find(context.TODO(), filter, opts) + if err != nil { + return nil, err + } + defer cursor.Close(context.TODO()) + + for cursor.Next(context.TODO()) { + var event relay.Event + if err := cursor.Decode(&event); err != nil { + return nil, err + } + results = append(results, event) + } + + if err := cursor.Err(); err != nil { + return nil, err + } + } + + return results, nil +} diff --git a/web/views/index.html b/web/views/index.html index 3848520..a32e50b 100644 --- a/web/views/index.html +++ b/web/views/index.html @@ -1,5 +1,16 @@ {{define "view"}}
You are now viewing the {{.Title}}
+

Top Ten Most Recent Events

+
{{end}}