blob: 93788f0019921f28268597e4839fa5ea65698551 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
package meta
import (
"slices"
"github.com/gofiber/fiber/v2"
"gorm.io/gorm"
)
type Sorting struct {
Field string
Direction string
}
func Sort(context *fiber.Ctx, allowedFields []string, fallbackField string) Sorting {
requestData := Request(context)
field := fallbackField
direction := "desc"
if sortValue := requestData.Query("sort"); sortValue != "" {
if slices.Contains(allowedFields, sortValue) {
field = sortValue
}
}
if orderValue := requestData.Query("order"); orderValue != "" {
switch orderValue {
case "asc", "desc":
direction = orderValue
}
}
return Sorting{Field: field, Direction: direction}
}
func (self Sorting) Apply(query *gorm.DB) *gorm.DB {
return query.Order(self.Field + " " + self.Direction)
}
|