brunel/handlers/packages/packages.go

74 lines
1.8 KiB
Go
Raw Normal View History

2024-07-28 20:59:50 +02:00
package handlers_packages
import (
"brunel/domain"
"brunel/packages"
2024-07-30 03:07:55 +02:00
"sort"
2024-07-28 20:59:50 +02:00
"strings"
"github.com/gofiber/fiber/v2"
)
2024-07-29 17:39:11 +02:00
type PackagesResponse struct {
2024-07-30 03:07:55 +02:00
Total int `json:"total"`
Packages []domain.SourcePackage `json:"packages"`
2024-07-29 17:39:11 +02:00
}
2024-07-28 20:59:50 +02:00
func Packages(c *fiber.Ctx) error {
2024-07-29 17:39:11 +02:00
pageNum := c.QueryInt("page", 1)
pageSize := c.QueryInt("pageSize", 250)
2024-07-29 01:46:05 +02:00
search := strings.ToLower(c.Query("search"))
2024-07-28 20:59:50 +02:00
filter := c.Query("filter")
2024-07-29 01:46:05 +02:00
// Adjust pageNum to be 0-based for GetPage
adjustedPageNum := pageNum - 1
if adjustedPageNum < 0 {
adjustedPageNum = 0
2024-07-28 20:59:50 +02:00
}
2024-07-29 01:46:05 +02:00
2024-07-28 20:59:50 +02:00
packs := packages.GetPackages()
2024-07-30 03:07:55 +02:00
finalReturn := make([]domain.SourcePackage, 0)
2024-07-30 02:24:18 +02:00
packs.ForEach(func(k string, source domain.SourcePackage) bool {
2024-07-29 01:46:05 +02:00
matchesFilter := filter == ""
matchesSearch := search == "" || strings.Contains(strings.ToLower(k), search)
2024-07-30 02:24:18 +02:00
source.Packages.ForEach(func(key string, value domain.PackageInfo) bool {
2024-07-29 01:46:05 +02:00
if !matchesFilter && value.Status == domain.PackageStatus(filter) {
matchesFilter = true
}
if !matchesSearch && strings.Contains(strings.ToLower(key), search) {
matchesSearch = true
}
return !(matchesFilter && matchesSearch)
2024-07-28 20:59:50 +02:00
})
2024-07-29 01:46:05 +02:00
if matchesFilter && matchesSearch {
2024-07-30 03:07:55 +02:00
finalReturn = append(finalReturn, source)
2024-07-28 20:59:50 +02:00
}
return true
})
2024-07-30 03:07:55 +02:00
sort.Slice(finalReturn, func(i, j int) bool {
return finalReturn[i].Name < finalReturn[j].Name
})
2024-07-30 03:22:38 +02:00
var result []domain.SourcePackage
startIndex := adjustedPageNum * pageSize
endIndex := (adjustedPageNum + 1) * pageSize
if startIndex >= len(finalReturn) {
result = []domain.SourcePackage{}
} else {
if endIndex > len(finalReturn) {
endIndex = len(finalReturn)
}
result = finalReturn[startIndex:endIndex]
}
2024-07-29 01:46:05 +02:00
2024-07-29 17:39:11 +02:00
response := PackagesResponse{
2024-07-30 03:07:55 +02:00
Total: len(finalReturn),
2024-07-29 17:39:11 +02:00
Packages: result,
}
return c.Status(fiber.StatusOK).JSON(response)
2024-07-28 20:59:50 +02:00
}