Skip to content

Commit

Permalink
Support sorting parameters
Browse files Browse the repository at this point in the history
  • Loading branch information
abaldeweg authored Feb 5, 2025
1 parent 37bb212 commit 5d5838f
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 14 deletions.
25 changes: 14 additions & 11 deletions logs_web/controller/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,24 +9,27 @@ import (

// GetEvents handles the GET request to retrieve logs.
func GetEvents(c *gin.Context) {
var filter map[string]interface{}
if err := c.ShouldBindJSON(&filter); err != nil {
var options struct {
Filter map[string]interface{} `json:"filter"`
Sort map[string]int `json:"sort"`
}
if err := c.ShouldBindJSON(&options); err != nil {
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "Invalid JSON"})
return
}

h, err := db.NewDBHandler()
if err != nil {
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "Internal Server Error"})
return
}
if err != nil {
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "Internal Server Error"})
return
}
defer h.Close()

d, err := h.FindDemanded(filter)
if err != nil {
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "Internal Server Error"})
return
}
d, err := h.FindDemanded(options.Filter, options.Sort)
if err != nil {
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "Internal Server Error"})
return
}

c.JSON(http.StatusOK, d)
}
10 changes: 7 additions & 3 deletions logs_web/db/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,14 @@ func (handler *DBHandler) Close() error {
return handler.client.Disconnect(context.TODO())
}

// FindDemanded retrieves logs based on the provided filter.
func (handler *DBHandler) FindDemanded(filter map[string]interface{}) ([]entity.LogEntry, error) {
// FindDemanded retrieves logs based on the provided filter and sorts them by the provided sort fields.
func (handler *DBHandler) FindDemanded(filter map[string]interface{}, sortFields map[string]int) ([]entity.LogEntry, error) {
bsonFilter := bson.M(filter)
cursor, err := handler.collection.Find(context.TODO(), bsonFilter)
findOptions := options.Find().SetSort(bson.D{})
for field, order := range sortFields {
findOptions.Sort = append(findOptions.Sort.(bson.D), bson.E{Key: field, Value: order})
}
cursor, err := handler.collection.Find(context.TODO(), bsonFilter, findOptions)
if err != nil {
return nil, err
}
Expand Down
3 changes: 3 additions & 0 deletions logs_web/openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ paths:
"time": {
"$gte": "2025-01-17T00:00:00Z",
"$lte": "2025-01-31T23:59:59Z"
},
"sort": {
"time": -1
}
}
responses:
Expand Down

0 comments on commit 5d5838f

Please sign in to comment.