aboutsummaryrefslogtreecommitdiff
path: root/utils/meta/sorting.go
diff options
context:
space:
mode:
Diffstat (limited to 'utils/meta/sorting.go')
-rw-r--r--utils/meta/sorting.go39
1 files changed, 39 insertions, 0 deletions
diff --git a/utils/meta/sorting.go b/utils/meta/sorting.go
new file mode 100644
index 0000000..93788f0
--- /dev/null
+++ b/utils/meta/sorting.go
@@ -0,0 +1,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)
+}