Blogs listing + Categories
This commit is contained in:
@@ -10,11 +10,17 @@ import (
|
||||
)
|
||||
|
||||
func HandleGetBlogs(w http.ResponseWriter, r *http.Request) {
|
||||
category := r.URL.Query().Get("category")
|
||||
var blog []models.Blog
|
||||
count, err := core.DB.NewSelect().
|
||||
q := core.DB.NewSelect().
|
||||
Model(&blog).
|
||||
Relation("Author").
|
||||
ScanAndCount(context.Background())
|
||||
Relation("Author")
|
||||
|
||||
if len(category) > 0 {
|
||||
q.Where("category = ?", category)
|
||||
}
|
||||
|
||||
count, err := q.ScanAndCount(context.Background())
|
||||
if err != nil {
|
||||
core.JSONError{
|
||||
Status: core.Error,
|
||||
|
||||
41
backend/api/blogs/categories.go
Normal file
41
backend/api/blogs/categories.go
Normal file
@@ -0,0 +1,41 @@
|
||||
package blogs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"fr.latosa-escrima/core"
|
||||
"fr.latosa-escrima/core/models"
|
||||
)
|
||||
|
||||
func HandleCategories(w http.ResponseWriter, r *http.Request) {
|
||||
var categories []struct {
|
||||
Category string `json:"category"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
err := core.DB.NewSelect().
|
||||
Model((*models.Blog)(nil)).
|
||||
Column("category").
|
||||
ColumnExpr("COUNT(*) AS count").
|
||||
Where("category IS NOT NULL AND category != ''").
|
||||
Group("category").
|
||||
// Count the occurrences of each distinct category
|
||||
Having("COUNT(category) > 0").
|
||||
// Sort the results by the count in descending order
|
||||
Order("count DESC").
|
||||
Scan(context.Background(), &categories)
|
||||
|
||||
if err != nil {
|
||||
core.JSONError{
|
||||
Status: core.Error,
|
||||
Message: err.Error(),
|
||||
}.Respond(w, http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
core.JSONSuccess{
|
||||
Status: core.Success,
|
||||
Message: "Categories found.",
|
||||
Data: categories,
|
||||
}.Respond(w, http.StatusOK)
|
||||
}
|
||||
Reference in New Issue
Block a user