brunel/handlers/packages/packages.go
2024-07-29 22:49:20 +01:00

62 lines
1.5 KiB
Go

package handlers_packages
import (
"brunel/domain"
"brunel/fastmap"
"brunel/packages"
"strings"
"github.com/gofiber/fiber/v2"
)
type PackagesResponse struct {
Total int `json:"total"`
Packages *fastmap.Fastmap[string, domain.SourcePackage] `json:"packages"`
}
func Packages(c *fiber.Ctx) error {
pageNum := c.QueryInt("page", 1)
pageSize := c.QueryInt("pageSize", 250)
search := strings.ToLower(c.Query("search"))
filter := c.Query("filter")
// Adjust pageNum to be 0-based for GetPage
adjustedPageNum := pageNum - 1
if adjustedPageNum < 0 {
adjustedPageNum = 0
}
packs := packages.GetPackages()
finalReturn := fastmap.New[string, domain.SourcePackage]()
packs.Iter(func(k string, source domain.SourcePackage) bool {
matchesFilter := filter == ""
matchesSearch := search == "" || strings.Contains(strings.ToLower(k), search)
source.Packages.Iter(func(key string, value domain.PackageInfo) bool {
if !matchesFilter && value.Status == domain.PackageStatus(filter) {
matchesFilter = true
}
if !matchesSearch && strings.Contains(strings.ToLower(key), search) {
matchesSearch = true
}
return !(matchesFilter && matchesSearch)
})
if matchesFilter && matchesSearch {
finalReturn.Set(k, source)
}
return true
})
result := finalReturn.GetPage(adjustedPageNum, pageSize)
response := PackagesResponse{
Total: finalReturn.Len(),
Packages: result,
}
return c.Status(fiber.StatusOK).JSON(response)
}