refactor trending history retrieval: clean up whitespace and improve code readability

This commit is contained in:
highperfocused 2025-03-08 22:20:19 +01:00
parent 4aac6b6afa
commit f98b118168
3 changed files with 17 additions and 17 deletions

View File

@ -283,45 +283,45 @@ func main() {
// Parse query parameters for pagination
limitStr := r.URL.Query().Get("limit")
offsetStr := r.URL.Query().Get("offset")
limit := 10 // Default limit
offset := 0 // Default offset
if limitStr != "" {
if val, err := strconv.Atoi(limitStr); err == nil && val > 0 {
limit = val
}
}
if offsetStr != "" {
if val, err := strconv.Atoi(offsetStr); err == nil && val >= 0 {
offset = val
}
}
// Get trending history for kind 20
history, err := trending.GetTrendingHistoryForKind(db.DB.DB, 20, limit, offset)
if err != nil {
http.Error(w, fmt.Sprintf("Error getting trending history: %v", err), http.StatusInternalServerError)
return
}
// Get total count for pagination info
totalCount, err := trending.GetTrendingHistoryCount(db.DB.DB, 20)
if err != nil {
http.Error(w, fmt.Sprintf("Error getting trending history count: %v", err), http.StatusInternalServerError)
return
}
response := map[string]interface{}{
"history": history,
"pagination": map[string]interface{}{
"total": totalCount,
"limit": limit,
"total": totalCount,
"limit": limit,
"offset": offset,
},
}
if err := json.NewEncoder(w).Encode(response); err != nil {
http.Error(w, fmt.Sprintf("Error encoding JSON: %v", err), http.StatusInternalServerError)
}
@ -330,7 +330,7 @@ func main() {
// Add UI for trending history
mux.HandleFunc("/trending/history", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("content-type", "text/html")
fmt.Fprintf(w, `
<!DOCTYPE html>
<html lang="en">

View File

@ -134,23 +134,23 @@ func calculateTrendingKind20(db *sql.DB) ([]Post, error) {
// Update in-memory cache
trendingCache.Set("trending_kind_20", trendingPosts, cacheDuration)
// Save to database for historical records
postsJSON, err := json.Marshal(trendingPosts)
if err != nil {
return nil, fmt.Errorf("failed to marshal trending posts to JSON: %w", err)
}
_, err = db.Exec(`
INSERT INTO trending_history (calculation_time, kind, trending_data)
VALUES (NOW(), 20, $1)
`, postsJSON)
if err != nil {
fmt.Printf("Warning: failed to store trending data in database: %v\n", err)
// Don't return error here as we want to still return the trending posts even if saving fails
}
return trendingPosts, nil
}
@ -171,10 +171,10 @@ func GetTrendingHistoryCount(db *sql.DB, kind int) (int, error) {
FROM trending_history
WHERE kind = $1
`, kind).Scan(&count)
if err != nil {
return 0, fmt.Errorf("failed to count trending history: %w", err)
}
return count, nil
}

View File

@ -137,4 +137,4 @@ type TrendingHistoryEntry struct {
ID int `json:"id"`
CalculationTime time.Time `json:"calculation_time"`
Posts []Post `json:"posts"`
}
}