Better categories api

This commit is contained in:
LittleSheep 2024-12-22 14:35:19 +08:00
parent 0ceee18524
commit 6de2ef00a2
2 changed files with 30 additions and 5 deletions

View File

@ -2,6 +2,7 @@ package api
import ( import (
"git.solsynth.dev/hypernet/interactive/pkg/internal/http/exts" "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/interactive/pkg/internal/services"
"git.solsynth.dev/hypernet/nexus/pkg/nex/sec" "git.solsynth.dev/hypernet/nexus/pkg/nex/sec"
"github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2"
@ -19,9 +20,23 @@ func getCategory(c *fiber.Ctx) error {
} }
func listCategories(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 { if err != nil {
return fiber.NewError(fiber.StatusNotFound, err.Error()) return fiber.NewError(fiber.StatusInternalServerError, err.Error())
} }
return c.JSON(categories) return c.JSON(categories)

View File

@ -2,17 +2,27 @@ package services
import ( import (
"errors" "errors"
"git.solsynth.dev/hypernet/nexus/pkg/nex/cruda"
"strings" "strings"
"git.solsynth.dev/hypernet/nexus/pkg/nex/cruda"
"git.solsynth.dev/hypernet/interactive/pkg/internal/database" "git.solsynth.dev/hypernet/interactive/pkg/internal/database"
"git.solsynth.dev/hypernet/interactive/pkg/internal/models" "git.solsynth.dev/hypernet/interactive/pkg/internal/models"
"gorm.io/gorm" "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 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 return categories, err
} }