Sorting

Sort parameters use field,direction format. Multiple sort parameters are supported.

Query Format

?sort=name,desc&sort=id,asc

Multiple sort parameters are supported. Direction is optional and defaults to asc.

Parsing

Multiple Sorts

sorts := pageable.ParseSorts([]string{"name,desc", "id,asc"})
// [{name desc} {id asc}]

Single Sort

sort := pageable.ParseSort("name,desc")
// &Sort{Field: "name", Direction: DESC}

sort := pageable.ParseSort("name")
// &Sort{Field: "name", Direction: ASC}  (default)

Sort Safety

Always whitelist sort fields before using them in SQL:

req := pageable.PageRequestFromQuery(r.URL.Query()).
    SortableFields("id", "name", "created_at")

SortableFields removes any sort field not in the allowed list. This prevents users from injecting arbitrary column names into your queries.

Field names are also validated to only contain safe SQL identifier characters (letters, digits, underscores, and dots).

Field Mapping

Use MapSortFields to translate user-facing field names to database column names. This is useful when your API uses camelCase but your database uses snake_case:

req := pageable.PageRequestFromQuery(r.URL.Query()).
    SortableFields("id", "name", "createdAt").
    MapSortFields(map[string]string{
        "createdAt": "created_at",
    }).
    WithDefaultSort(pageable.Sort{Field: "created_at", Direction: pageable.DESC})

req.OrderBy() // "created_at desc, id asc"

Fields without a mapping entry are kept as-is. Place MapSortFields after SortableFields so that filtering uses the user-facing names and mapping produces the database names.

Default Sort

Apply a fallback sort when no valid sorts are provided:

req := pageable.PageRequestFromQuery(r.URL.Query()).
    SortableFields("id", "name", "created_at").
    WithDefaultSort(pageable.Sort{Field: "id", Direction: pageable.ASC})

OrderBy Helper

Generate an ORDER BY clause string:

req.OrderBy()
// "name desc, id asc"  (from query params)
// "id asc"             (fallback when no sort provided)
// ""                   (when no sorts at all)

Types

type Direction string

const (
    ASC  Direction = "asc"
    DESC Direction = "desc"
)

type Sort struct {
    Field     string
    Direction Direction
}

Sort.String() returns "field,direction" format: "name,desc".