-
Notifications
You must be signed in to change notification settings - Fork 3
/
options.go
85 lines (69 loc) · 1.85 KB
/
options.go
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
81
82
83
84
85
package patreon
import (
"net/url"
"reflect"
"regexp"
"strings"
)
type options struct {
fields map[string]string
include string
size int
cursor string
}
type requestOption func(*options)
// WithFields specifies the resource attributes you want to be returned by API.
func WithFields(resource string, fields ...string) requestOption {
return func(o *options) {
if o.fields == nil {
o.fields = make(map[string]string)
}
o.fields[resource] = strings.Join(fields, ",")
}
}
// WithIncludes specifies the related resources you want to be returned by API.
func WithIncludes(include ...string) requestOption {
return func(o *options) {
o.include = strings.Join(include, ",")
}
}
// WithPageSize specifies the number of items to return.
func WithPageSize(size int) requestOption {
return func(o *options) {
o.size = size
}
}
// WithCursor controls cursor-based pagination. Cursor will also be extracted from navigation links for convenience.
func WithCursor(cursor string) requestOption {
return func(o *options) {
u, err := url.ParseRequestURI(cursor)
if err == nil {
cursor = u.Query().Get("page[cursor]")
}
o.cursor = cursor
}
}
func getOptions(opts ...requestOption) options {
cfg := options{}
for _, fn := range opts {
fn(&cfg)
}
return cfg
}
// getObjectFields will get all fields for an object
func getObjectFields(i interface{}) []string {
v := reflect.ValueOf(i)
typeOfS := v.Type()
var fields []string
for i := 0; i < v.NumField(); i++ {
fields = append(fields, toSnakeCase(typeOfS.Field(i).Name))
}
return fields
}
var matchFirstCap = regexp.MustCompile("(.)([A-Z][a-z]+)")
var matchAllCap = regexp.MustCompile("([a-z0-9])([A-Z])")
func toSnakeCase(str string) string {
snake := matchFirstCap.ReplaceAllString(str, "${1}_${2}")
snake = matchAllCap.ReplaceAllString(snake, "${1}_${2}")
return strings.ToLower(snake)
}