feat: allow restful filter customization per field

This commit is contained in:
Deluan
2020-03-19 21:09:57 -04:00
parent 97d95ea794
commit 8cdd4e317d
2 changed files with 24 additions and 5 deletions
+3
View File
@@ -23,6 +23,9 @@ func NewAlbumRepository(ctx context.Context, o orm.Ormer) model.AlbumRepository
r.sortMappings = map[string]string{ r.sortMappings = map[string]string{
"artist": "compilation asc, album_artist asc, name asc", "artist": "compilation asc, album_artist asc, name asc",
} }
r.filterMappings = map[string]filterFunc{
"compilation": booleanFilter,
}
return r return r
} }
+21 -5
View File
@@ -15,11 +15,14 @@ import (
"github.com/google/uuid" "github.com/google/uuid"
) )
type filterFunc = func(field string, value interface{}) Sqlizer
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 sortMappings map[string]string
filterMappings map[string]filterFunc
} }
const invalidUserId = "-1" const invalidUserId = "-1"
@@ -226,10 +229,23 @@ func (r sqlRepository) parseRestOptions(options ...rest.QueryOptions) model.Quer
if len(options[0].Filters) > 0 { if len(options[0].Filters) > 0 {
filters := And{} filters := And{}
for f, v := range options[0].Filters { for f, v := range options[0].Filters {
filters = append(filters, Like{f: fmt.Sprintf("%s%%", v)}) if ff, ok := r.filterMappings[f]; ok {
filters = append(filters, ff(f, v))
} else {
filters = append(filters, startsWithFilter(f, v))
}
} }
qo.Filters = filters qo.Filters = filters
} }
} }
return qo return qo
} }
func startsWithFilter(field string, value interface{}) Like {
return Like{field: fmt.Sprintf("%s%%", value)}
}
func booleanFilter(field string, value interface{}) Sqlizer {
v := strings.ToLower(value.(string))
return Eq{field: strings.ToLower(v) == "true"}
}