add sort
This commit is contained in:
@@ -3,6 +3,8 @@ package libhelper
|
||||
import (
|
||||
"fmt"
|
||||
pl "simrs-vx/pkg/logger"
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"gorm.io/gorm"
|
||||
@@ -16,6 +18,59 @@ func SearchCodeOrName(search string, tx *gorm.DB) *gorm.DB {
|
||||
return tx
|
||||
}
|
||||
|
||||
func Sort(sort string, tx *gorm.DB) *gorm.DB {
|
||||
if sort == "" {
|
||||
return tx
|
||||
}
|
||||
|
||||
pairs := strings.Split(sort, ",")
|
||||
for _, pair := range pairs {
|
||||
parts := strings.Split(strings.TrimSpace(pair), "=")
|
||||
if len(parts) != 2 {
|
||||
continue // skip invalid format
|
||||
}
|
||||
|
||||
field := strings.TrimSpace(parts[0])
|
||||
direction := strings.ToUpper(strings.TrimSpace(parts[1]))
|
||||
|
||||
if direction != "ASC" && direction != "DESC" {
|
||||
continue
|
||||
}
|
||||
|
||||
field = normalizeColumnName(field)
|
||||
|
||||
tx = tx.Order(fmt.Sprintf("\"%s\" %s", field, direction))
|
||||
}
|
||||
|
||||
return tx
|
||||
}
|
||||
|
||||
func normalizeColumnName(input string) string {
|
||||
if input == "" {
|
||||
return input
|
||||
}
|
||||
|
||||
input = strings.ReplaceAll(input, "-", "_")
|
||||
|
||||
runes := []rune(input)
|
||||
var out []rune
|
||||
upperNext := true
|
||||
for _, r := range runes {
|
||||
if r == '_' {
|
||||
out = append(out, r)
|
||||
upperNext = true
|
||||
continue
|
||||
}
|
||||
if upperNext {
|
||||
out = append(out, unicode.ToUpper(r))
|
||||
upperNext = false
|
||||
} else {
|
||||
out = append(out, r)
|
||||
}
|
||||
}
|
||||
return string(out)
|
||||
}
|
||||
|
||||
func HandleCreateError(input any, event *pl.Event, err error) error {
|
||||
e, ok := err.(*pgconn.PgError)
|
||||
if !ok {
|
||||
|
||||
Reference in New Issue
Block a user