brunel/handlers/build/queue.go
2024-07-30 02:22:38 +01:00

71 lines
1.7 KiB
Go

package handlers_build
import (
"brunel/buildqueue"
"brunel/domain"
"sort"
"strings"
"github.com/gofiber/fiber/v2"
)
type QueueResponse struct {
Total int `json:"total"`
Packages []domain.BuildQueueItem `json:"packages"`
}
func Queue(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 := buildqueue.GetQueue()
finalReturn := make([]domain.BuildQueueItem, 0)
packs.ForEach(func(k string, source domain.BuildQueueItem) bool {
matchesSearch := search == "" || strings.Contains(strings.ToLower(k), search)
matchesFilter := filter == "" || source.Status == domain.BuildStatus(filter)
source.Source.Packages.ForEach(func(key string, value domain.PackageInfo) bool {
if !matchesSearch && strings.Contains(strings.ToLower(key), search) {
matchesSearch = true
}
return !(matchesSearch)
})
if matchesFilter && matchesSearch {
finalReturn = append(finalReturn, source)
}
return true
})
sort.Slice(finalReturn, func(i, j int) bool {
return finalReturn[i].Source.Name < finalReturn[j].Source.Name
})
var result []domain.BuildQueueItem
startIndex := adjustedPageNum * pageSize
endIndex := (adjustedPageNum + 1) * pageSize
if startIndex >= len(finalReturn) {
result = []domain.BuildQueueItem{}
} else {
if endIndex > len(finalReturn) {
endIndex = len(finalReturn)
}
result = finalReturn[startIndex:endIndex]
}
response := QueueResponse{
Total: len(finalReturn),
Packages: result,
}
return c.Status(fiber.StatusOK).JSON(response)
}