Ash Wilson | c8e6887 | 2014-09-16 10:36:56 -0400 | [diff] [blame] | 1 | package pagination |
| 2 | |
Jon Perritt | c7d828e | 2016-02-25 03:06:33 -0600 | [diff] [blame^] | 3 | import ( |
| 4 | "fmt" |
| 5 | "reflect" |
| 6 | ) |
| 7 | |
Ash Wilson | c8e6887 | 2014-09-16 10:36:56 -0400 | [diff] [blame] | 8 | // MarkerPage is a stricter Page interface that describes additional functionality required for use with NewMarkerPager. |
| 9 | // For convenience, embed the MarkedPageBase struct. |
| 10 | type MarkerPage interface { |
| 11 | Page |
| 12 | |
Ash Wilson | 7486351 | 2014-09-16 11:45:51 -0400 | [diff] [blame] | 13 | // LastMarker returns the last "marker" value on this page. |
| 14 | LastMarker() (string, error) |
Ash Wilson | c8e6887 | 2014-09-16 10:36:56 -0400 | [diff] [blame] | 15 | } |
| 16 | |
| 17 | // MarkerPageBase is a page in a collection that's paginated by "limit" and "marker" query parameters. |
| 18 | type MarkerPageBase struct { |
Ash Wilson | b8b16f8 | 2014-10-20 10:19:49 -0400 | [diff] [blame] | 19 | PageResult |
Ash Wilson | c8e6887 | 2014-09-16 10:36:56 -0400 | [diff] [blame] | 20 | |
Ash Wilson | 58c4f67 | 2014-09-16 11:50:56 -0400 | [diff] [blame] | 21 | // Owner is a reference to the embedding struct. |
| 22 | Owner MarkerPage |
Ash Wilson | c8e6887 | 2014-09-16 10:36:56 -0400 | [diff] [blame] | 23 | } |
| 24 | |
| 25 | // NextPageURL generates the URL for the page of results after this one. |
| 26 | func (current MarkerPageBase) NextPageURL() (string, error) { |
| 27 | currentURL := current.URL |
| 28 | |
Ash Wilson | 58c4f67 | 2014-09-16 11:50:56 -0400 | [diff] [blame] | 29 | mark, err := current.Owner.LastMarker() |
Ash Wilson | c8e6887 | 2014-09-16 10:36:56 -0400 | [diff] [blame] | 30 | if err != nil { |
| 31 | return "", err |
| 32 | } |
| 33 | |
| 34 | q := currentURL.Query() |
| 35 | q.Set("marker", mark) |
| 36 | currentURL.RawQuery = q.Encode() |
| 37 | |
| 38 | return currentURL.String(), nil |
| 39 | } |
Jon Perritt | db319f1 | 2015-02-17 19:32:40 -0700 | [diff] [blame] | 40 | |
Jon Perritt | c7d828e | 2016-02-25 03:06:33 -0600 | [diff] [blame^] | 41 | func (current MarkerPageBase) IsEmpty() (bool, error) { |
| 42 | if b, ok := current.Body.([]interface{}); ok { |
| 43 | return len(b) == 0, nil |
| 44 | } |
| 45 | return true, fmt.Errorf("Error while checking if MarkerPageBase was empty: expected []interface type for Body bot got %+v", reflect.TypeOf(current.Body)) |
| 46 | } |
| 47 | |
Jon Perritt | db319f1 | 2015-02-17 19:32:40 -0700 | [diff] [blame] | 48 | // GetBody returns the linked page's body. This method is needed to satisfy the |
| 49 | // Page interface. |
| 50 | func (current MarkerPageBase) GetBody() interface{} { |
| 51 | return current.Body |
| 52 | } |