feat: enable overriding sql sorting

This commit is contained in:
Deluan 2020-02-05 14:12:13 -05:00
parent 989deb1200
commit 7aab82c246
2 changed files with 33 additions and 8 deletions

View file

@ -21,6 +21,10 @@ func NewMediaFileRepository(ctx context.Context, o orm.Ormer) *mediaFileReposito
r.ctx = ctx r.ctx = ctx
r.ormer = o r.ormer = o
r.tableName = "media_file" r.tableName = "media_file"
r.sortMappings = map[string]string{
"artist": "artist asc, album asc, disc_number asc, track_number asc",
"album": "album asc, disc_number asc, track_number asc",
}
return r return r
} }

View file

@ -4,6 +4,7 @@ import (
"context" "context"
"fmt" "fmt"
"strings" "strings"
"text/scanner"
"time" "time"
. "github.com/Masterminds/squirrel" . "github.com/Masterminds/squirrel"
@ -15,9 +16,10 @@ import (
) )
type sqlRepository struct { type sqlRepository struct {
ctx context.Context ctx context.Context
tableName string tableName string
ormer orm.Ormer ormer orm.Ormer
sortMappings map[string]string
} }
const invalidUserId = "-1" const invalidUserId = "-1"
@ -55,11 +57,30 @@ func (r sqlRepository) applyOptions(sq SelectBuilder, options ...model.QueryOpti
sq = sq.Offset(uint64(options[0].Offset)) sq = sq.Offset(uint64(options[0].Offset))
} }
if options[0].Sort != "" { if options[0].Sort != "" {
if options[0].Order == "desc" { sort := toSnakeCase(options[0].Sort)
sq = sq.OrderBy(toSnakeCase(options[0].Sort + " desc")) if mapping, ok := r.sortMappings[sort]; ok {
} else { sort = mapping
sq = sq.OrderBy(toSnakeCase(options[0].Sort))
} }
if !strings.Contains(sort, "asc") && !strings.Contains(sort, "desc") {
sort = sort + " asc"
}
if options[0].Order == "desc" {
var s scanner.Scanner
s.Init(strings.NewReader(sort))
var newSort string
for tok := s.Scan(); tok != scanner.EOF; tok = s.Scan() {
switch s.TokenText() {
case "asc":
newSort += " " + "desc"
case "desc":
newSort += " " + "asc"
default:
newSort += " " + s.TokenText()
}
}
sort = newSort
}
sq = sq.OrderBy(sort)
} }
} }
return sq return sq
@ -190,7 +211,7 @@ func (r sqlRepository) parseRestOptions(options ...rest.QueryOptions) model.Quer
qo := model.QueryOptions{} qo := model.QueryOptions{}
if len(options) > 0 { if len(options) > 0 {
qo.Sort = options[0].Sort qo.Sort = options[0].Sort
qo.Order = options[0].Order qo.Order = strings.ToLower(options[0].Order)
qo.Max = options[0].Max qo.Max = options[0].Max
qo.Offset = options[0].Offset qo.Offset = options[0].Offset
if len(options[0].Filters) > 0 { if len(options[0].Filters) > 0 {