From 6de2ef00a232ceb360201ed89ca3940008ad4201 Mon Sep 17 00:00:00 2001 From: LittleSheep Date: Sun, 22 Dec 2024 14:35:19 +0800 Subject: [PATCH] :sparkles: Better categories api --- pkg/internal/http/api/categories_api.go | 19 +++++++++++++++++-- pkg/internal/services/categories.go | 16 +++++++++++++--- 2 files changed, 30 insertions(+), 5 deletions(-) diff --git a/pkg/internal/http/api/categories_api.go b/pkg/internal/http/api/categories_api.go index ec92b10..908e726 100644 --- a/pkg/internal/http/api/categories_api.go +++ b/pkg/internal/http/api/categories_api.go @@ -2,6 +2,7 @@ package api import ( "git.solsynth.dev/hypernet/interactive/pkg/internal/http/exts" + "git.solsynth.dev/hypernet/interactive/pkg/internal/models" "git.solsynth.dev/hypernet/interactive/pkg/internal/services" "git.solsynth.dev/hypernet/nexus/pkg/nex/sec" "github.com/gofiber/fiber/v2" @@ -19,9 +20,23 @@ func getCategory(c *fiber.Ctx) error { } func listCategories(c *fiber.Ctx) error { - categories, err := services.ListCategory() + take := c.QueryInt("take", 0) + offset := c.QueryInt("offset", 0) + probe := c.Query("probe") + + if take > 100 { + take = 100 + } + + var categories []models.Category + var err error + if len(probe) > 0 { + categories, err = services.SearchCategories(take, offset, probe) + } else { + categories, err = services.ListCategory(take, offset) + } if err != nil { - return fiber.NewError(fiber.StatusNotFound, err.Error()) + return fiber.NewError(fiber.StatusInternalServerError, err.Error()) } return c.JSON(categories) diff --git a/pkg/internal/services/categories.go b/pkg/internal/services/categories.go index 9f942b0..7f2a4f7 100644 --- a/pkg/internal/services/categories.go +++ b/pkg/internal/services/categories.go @@ -2,17 +2,27 @@ package services import ( "errors" - "git.solsynth.dev/hypernet/nexus/pkg/nex/cruda" "strings" + "git.solsynth.dev/hypernet/nexus/pkg/nex/cruda" + "git.solsynth.dev/hypernet/interactive/pkg/internal/database" "git.solsynth.dev/hypernet/interactive/pkg/internal/models" "gorm.io/gorm" ) -func ListCategory() ([]models.Category, error) { +func SearchCategories(take int, offset int, probe string) ([]models.Category, error) { + probe = "%" + probe + "%" + var categories []models.Category - err := database.C.Find(&categories).Error + err := database.C.Where("alias LIKE ?", probe).Offset(offset).Limit(take).Find(&categories).Error + + return categories, err +} + +func ListCategory(take int, offset int) ([]models.Category, error) { + var categories []models.Category + err := database.C.Offset(offset).Limit(take).Find(&categories).Error return categories, err }