From a47d2d06fac08a05be8123142562f0a5045ba830 Mon Sep 17 00:00:00 2001 From: Ewan Harris Date: Tue, 24 Oct 2023 12:11:09 +0100 Subject: [PATCH] Add a Sort RequestOption helper --- EXAMPLES.md | 1 + management/management_request.go | 10 ++++++++++ management/management_test.go | 11 +++++++++++ 3 files changed, 22 insertions(+) diff --git a/EXAMPLES.md b/EXAMPLES.md index b02979ff..8c04d8c0 100644 --- a/EXAMPLES.md +++ b/EXAMPLES.md @@ -33,6 +33,7 @@ management.PerPage() management.IncludeTotals() management.Take() management.From() +management.Sort() ``` ## Pagination diff --git a/management/management_request.go b/management/management_request.go index 0891bea1..9d284afc 100644 --- a/management/management_request.go +++ b/management/management_request.go @@ -285,3 +285,13 @@ func Stringify(v interface{}) string { } return string(b) } + +// Sort configures a request to sort data by the selected field. +// Use 1 to sort ascending and -1 to sort descending. +func Sort(sort string) RequestOption { + return newRequestOption(func(r *http.Request) { + q := r.URL.Query() + q.Set("sort", sort) + r.URL.RawQuery = q.Encode() + }) +} diff --git a/management/management_test.go b/management/management_test.go index a8251490..c08cffbb 100644 --- a/management/management_test.go +++ b/management/management_test.go @@ -157,6 +157,17 @@ func TestOptionDefaults(t *testing.T) { assert.Equal(t, "false", includeTotals) } +func TestOptionSort(t *testing.T) { + r, _ := http.NewRequest("GET", "/", nil) + + Sort("name:-1").apply(r) + + v := r.URL.Query() + + sort := v.Get("sort") + assert.Equal(t, "name:-1", sort) +} + func TestStringify(t *testing.T) { expected := `{ "foo": "bar"