blob: 0376edbaf003252c1da950707ef74b4424b522ac [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 {
7 LastHTTPResponse
8
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
42 fmt.Printf("key = %#v, path = %#v, value = %#v\n", key, path, value)
43
44 if len(path) > 0 {
45 submap, ok = value.(map[string]interface{})
46 if !ok {
47 return "", fmt.Errorf("Expected an object, but was %#v", value)
48 }
49 } else {
50 if value == nil {
51 // Actual null element.
52 return "", nil
53 }
54
55 url, ok := value.(string)
56 if !ok {
57 return "", fmt.Errorf("Expected a string, but was %#v", value)
58 }
59
60 return url, nil
61 }
62 }
Ash Wilsonc8e68872014-09-16 10:36:56 -040063}