Files
2026-08-04 12:50:20 +05:00

59 lines
1.6 KiB
Go

// Package listing provides common query parameters for admin list endpoints:
// pagination, search and sorting.
package listing
import (
"fmt"
"strconv"
"strings"
"github.com/gin-gonic/gin"
)
// Params holds common list query options.
type Params struct {
Limit int
Page int
Search string
Sort string
Order string
}
// FromQuery extracts list params from the request query string.
func FromQuery(c *gin.Context) Params {
limit, _ := strconv.Atoi(c.Query("limit"))
page, _ := strconv.Atoi(c.Query("page"))
return Params{
Limit: limit,
Page: page,
Search: strings.TrimSpace(c.Query("search")),
Sort: c.Query("sort"),
Order: strings.ToLower(c.Query("order")),
}
}
// Paginated reports whether pagination should be applied.
// Mirrors the pre-existing behaviour: limit=0 or page=0 returns all rows.
func (p Params) Paginated() bool { return p.Limit > 0 && p.Page > 0 }
// Offset returns the SQL offset for the current page.
func (p Params) Offset() int { return (p.Page - 1) * p.Limit }
// SearchPattern returns an ILIKE pattern for the search term.
func (p Params) SearchPattern() string { return "%" + p.Search + "%" }
// OrderClause returns a safe ORDER BY clause. The requested sort key is looked
// up in the whitelist map (query key -> SQL column); unknown or empty keys fall
// back to the def expression. User input is never interpolated directly.
func (p Params) OrderClause(whitelist map[string]string, def string) string {
col, ok := whitelist[p.Sort]
if !ok {
return " ORDER BY " + def + " "
}
dir := "DESC"
if p.Order == "asc" {
dir = "ASC"
}
return fmt.Sprintf(" ORDER BY %s %s ", col, dir)
}