From 65d344a21e2e3334c486a1a5c22524a76fd969f4 Mon Sep 17 00:00:00 2001 From: Marvin Zhang Date: Thu, 27 Mar 2025 11:55:22 +0800 Subject: [PATCH] refactor: enhance sorting logic in GetSortsFromString function - Replaced JSON unmarshalling with string parsing to handle sorting parameters more flexibly. - Improved handling of sorting direction by allowing both ascending and descending specifications through prefixes. - Enhanced code readability and maintainability by simplifying the sorting logic and removing unnecessary error handling. --- core/controllers/utils.go | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/core/controllers/utils.go b/core/controllers/utils.go index 8ae3951d..c5aa77e7 100644 --- a/core/controllers/utils.go +++ b/core/controllers/utils.go @@ -191,8 +191,31 @@ func GetSortsFromString(sortStr string) (sorts []entity.Sort, err error) { if sortStr == "" { return nil, nil } - if err := json.Unmarshal([]byte(sortStr), &sorts); err != nil { - return nil, err + parts := strings.Split(sortStr, ",") + for _, part := range parts { + trimmed := strings.TrimSpace(part) + if trimmed == "" { + continue + } + if !strings.HasPrefix(trimmed, "-") { + key := strings.TrimLeft(trimmed, "+") + sorts = append(sorts, entity.Sort{ + Key: key, + Direction: constants.DESCENDING, + }) + } else if strings.HasPrefix(trimmed, "+") { + key := strings.TrimLeft(trimmed, "+") + sorts = append(sorts, entity.Sort{ + Key: key, + Direction: constants.ASCENDING, + }) + } else { + key := strings.TrimLeft(trimmed, "-") + sorts = append(sorts, entity.Sort{ + Key: key, + Direction: constants.ASCENDING, + }) + } } return sorts, nil }