blob: 461fa499afc64af9ca63cd97e7198f6532d6a7fa [file] [log] [blame]
Ash Wilsonc8e68872014-09-16 10:36:56 -04001package pagination
2
Ash Wilsonfc55c822014-09-25 13:18:16 -04003import "fmt"
Ash Wilsonc8e68872014-09-16 10:36:56 -04004
5// LinkedPageBase may be embedded to implement a page that provides navigational "Next" and "Previous" links within its result.
Ash Wilsonfc55c822014-09-25 13:18:16 -04006type LinkedPageBase struct {
Ash Wilsonb8b16f82014-10-20 10:19:49 -04007 PageResult
Ash Wilsonfc55c822014-09-25 13:18:16 -04008
9 // LinkPath lists the keys that should be traversed within a response to arrive at the "next" pointer.
10 // If any link along the path is missing, an empty URL will be returned.
11 // If any link results in an unexpected value type, an error will be returned.
12 // When left as "nil", []string{"links", "next"} will be used as a default.
13 LinkPath []string
14}
Ash Wilsonc8e68872014-09-16 10:36:56 -040015
16// NextPageURL extracts the pagination structure from a JSON response and returns the "next" link, if one is present.
17// It assumes that the links are available in a "links" element of the top-level response object.
18// If this is not the case, override NextPageURL on your result type.
19func (current LinkedPageBase) NextPageURL() (string, error) {
Ash Wilsonfc55c822014-09-25 13:18:16 -040020 var path []string
21 var key string
22
23 if current.LinkPath == nil {
24 path = []string{"links", "next"}
25 } else {
26 path = current.LinkPath
Ash Wilsonc8e68872014-09-16 10:36:56 -040027 }
28
Ash Wilsonfc55c822014-09-25 13:18:16 -040029 submap, ok := current.Body.(map[string]interface{})
30 if !ok {
31 return "", fmt.Errorf("Expected an object, but was %#v", current.Body)
Ash Wilsonc8e68872014-09-16 10:36:56 -040032 }
33
Ash Wilsonfc55c822014-09-25 13:18:16 -040034 for {
35 key, path = path[0], path[1:len(path)]
Ash Wilsonc8e68872014-09-16 10:36:56 -040036
Ash Wilsonfc55c822014-09-25 13:18:16 -040037 value, ok := submap[key]
38 if !ok {
39 return "", nil
40 }
41
Ash Wilsonfc55c822014-09-25 13:18:16 -040042 if len(path) > 0 {
43 submap, ok = value.(map[string]interface{})
44 if !ok {
45 return "", fmt.Errorf("Expected an object, but was %#v", value)
46 }
47 } else {
48 if value == nil {
49 // Actual null element.
50 return "", nil
51 }
52
53 url, ok := value.(string)
54 if !ok {
55 return "", fmt.Errorf("Expected a string, but was %#v", value)
56 }
57
58 return url, nil
59 }
60 }
Ash Wilsonc8e68872014-09-16 10:36:56 -040061}