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) }