frontend showing top 10 recent events, no formatting

This commit is contained in:
Chris kerr 2024-07-27 15:59:08 -04:00
parent b312dfe480
commit 46c9e4af3c
2 changed files with 74 additions and 8 deletions

View File

@ -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
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
}

View File

@ -1,5 +1,16 @@
{{define "view"}}
<main class="flex flex-col items-center justify-center p-8">
<div class="mb-4">You are now viewing the {{.Title}}</div>
<h2>Top Ten Most Recent Events</h2>
<ul>
{{range .Events}}
<li>
<strong>ID:</strong> {{.ID}}<br />
<strong>Content:</strong> {{.Content}}<br />
<strong>Created At:</strong> {{.CreatedAt}}<br />
<strong>PubKey:</strong> {{.PubKey}}
</li>
{{end}}
</ul>
</main>
{{end}}