Skip to content

Commit

Permalink
Add a Sort RequestOption helper
Browse files Browse the repository at this point in the history
  • Loading branch information
ewanharris committed Oct 24, 2023
1 parent 1f406ac commit a47d2d0
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 0 deletions.
1 change: 1 addition & 0 deletions EXAMPLES.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ management.PerPage()
management.IncludeTotals()
management.Take()
management.From()
management.Sort()
```

## Pagination
Expand Down
10 changes: 10 additions & 0 deletions management/management_request.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
})
}
11 changes: 11 additions & 0 deletions management/management_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down

0 comments on commit a47d2d0

Please sign in to comment.