-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathpage_util.go
More file actions
80 lines (67 loc) · 2.02 KB
/
Copy pathpage_util.go
File metadata and controls
80 lines (67 loc) · 2.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package client
import (
"context"
"encoding/json"
"fmt"
"strings"
)
// Takes a limit on the max number of records to read and a max pageSize and calculates the max number of pages to read.
func ReadLimits(pageSize *int, limit *int) int {
//don't care about pageSize
if pageSize == nil {
if limit == nil {
//don't care about the limit either
return 50 //default
}
//return the most efficient pageSize
return min(*limit, 1000)
} else {
if limit == nil {
//we care about the pageSize but not the limit
return *pageSize
}
return min(*pageSize, *limit)
}
}
func GetNext(baseUrl string, response interface{}, getNextPage func(ctx context.Context, nextPageUri string) (interface{}, error)) (interface{}, error) {
return GetNextWithContext(context.Background(), baseUrl, response, getNextPage)
}
func GetNextWithContext(ctx context.Context, baseUrl string, response interface{}, getNextPage func(ctx context.Context, nextPageUri string) (interface{}, error)) (interface{}, error) {
nextPageUrl, err := getNextPageUrl(baseUrl, response)
if err != nil {
return nil, err
}
return getNextPage(ctx, nextPageUrl)
}
func toMap(s interface{}) (map[string]interface{}, error) {
var payload map[string]interface{}
data, err := json.Marshal(s)
if err != nil {
return nil, err
}
err = json.Unmarshal(data, &payload)
if err != nil {
return nil, err
}
return payload, err
}
func getNextPageUrl(baseUrl string, response interface{}) (string, error) {
payload, err := toMap(response)
if err != nil {
return "", err
}
if payload != nil && payload["meta"] != nil && payload["meta"].(map[string]interface{})["next_page_url"] != nil {
return payload["meta"].(map[string]interface{})["next_page_url"].(string), nil
}
if payload != nil && payload["next_page_uri"] != nil {
// remove any leading and trailing '/'
return fmt.Sprintf("%s/%s", strings.Trim(baseUrl, "/"), strings.Trim(payload["next_page_uri"].(string), "/")), nil
}
return "", nil
}
func min(a int, b int) int {
if a > b {
return b
}
return a
}