Skip to content

Commit

Permalink
Add MaxLimit.
Browse files Browse the repository at this point in the history
  • Loading branch information
gillesfabio committed Feb 9, 2016
1 parent 160d6b3 commit 2bd207f
Show file tree
Hide file tree
Showing 4 changed files with 18 additions and 0 deletions.
3 changes: 3 additions & 0 deletions defaults.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ const (
// DefaultLimit is the default number of items per page.
DefaultLimit = 20

// DefaultMaxLimit is the default maximum limit that can be set.
DefaultMaxLimit = 20

// DefaultLimitKeyName is the request key name.
DefaultLimitKeyName = "limit"

Expand Down
4 changes: 4 additions & 0 deletions paginator.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ type Options struct {
// DefaultLimit is the default number of items per page.
DefaultLimit int64

// MaxLimit is the maximum limit that can be set.
MaxLimit int64

// LimitKeyName is the query string key name for the limit.
LimitKeyName string

Expand All @@ -27,6 +30,7 @@ type Options struct {
func NewOptions() *Options {
return &Options{
DefaultLimit: int64(DefaultLimit),
MaxLimit: int64(DefaultMaxLimit),
LimitKeyName: DefaultLimitKeyName,
OffsetKeyName: DefaultOffsetKeyName,
}
Expand Down
4 changes: 4 additions & 0 deletions utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ func GetLimitFromRequest(request *http.Request, options *Options) int64 {
limit, err = strconv.ParseInt(requestLimit, 10, 64)
if err != nil {
limit = options.DefaultLimit

}
if limit > options.MaxLimit {
limit = options.MaxLimit
}
} else {
limit = options.DefaultLimit
Expand Down
7 changes: 7 additions & 0 deletions utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ func TestGetLimitFromRequest(t *testing.T) {
a := assert.New(t)

options := NewOptions()
options.MaxLimit = 100

// We define a default limit...
options.DefaultLimit = 40
Expand All @@ -46,6 +47,12 @@ func TestGetLimitFromRequest(t *testing.T) {
options.LimitKeyName = "perpage"
request, _ = http.NewRequest("GET", "http://example.com/?perpage=56", nil)
a.Equal(int64(56), GetLimitFromRequest(request, options))

// We restrict with a max limit
options.MaxLimit = 15
options.LimitKeyName = "limit"
request, _ = http.NewRequest("GET", "http://example.com/?limit=100", nil)
a.Equal(int64(15), GetLimitFromRequest(request, options))
}

func TestGetOffsetFromRequest(t *testing.T) {
Expand Down

0 comments on commit 2bd207f

Please sign in to comment.