-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhelpscout.go
97 lines (76 loc) · 1.98 KB
/
helpscout.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
86
87
88
89
90
91
92
93
94
95
96
97
package helpscout
import (
"fmt"
"net/url"
"time"
"github.com/pkg/errors"
)
var ErrorInterrupted = errors.New("")
const helpscoutApiEndpoint = "https://api.helpscout.net/v2"
type Page struct {
Size uint `json:"size"`
TotalElements uint `json:"totalElements"`
TotalPages uint `json:"totalPages"`
Number uint `json:"number"`
}
type generalListApiCallReq struct {
Embedded interface{} `json:"_embedded"`
Page Page `json:"page"`
}
type Client struct {
httpClient *httpClient
auth *auth
}
func NewClient(appId string, appKey string) *Client {
httpClient := newHttpClient()
return &Client{
httpClient: httpClient,
auth: newAuth(httpClient, appId, appKey),
}
}
func (c *Client) AuthKey(forceUpdate bool) (string, error) {
token, err := c.auth.getToken(forceUpdate)
if err != nil {
return "", errors.Wrap(err, "Unable to update Auth Token")
}
return token, nil
}
func (c *Client) SetAuthKey(key string, expTime time.Time) {
c.auth.token = key
c.auth.tokenExpireTime = expTime
}
func (c *Client) doApiCall(method string, resource string, query *url.Values,
reqData interface{}, respData interface{}) error {
repeatAllCnt := 0
forceTokenUpdate := false
for {
token, err := c.auth.getToken(forceTokenUpdate)
if err != nil {
return errors.Wrap(err, "Unable to update Auth Token")
}
url := helpscoutApiEndpoint + resource
authHeader := make(map[string]string)
authHeader["Authorization"] = fmt.Sprintf("Bearer %s", token)
repeatCnt := 0
for {
err := c.httpClient.doRequest(url, method, authHeader, query, reqData, respData)
if err == ErrorRateLimit {
time.Sleep(time.Second)
repeatCnt++
if repeatCnt > 10 {
return errors.New("Unable to submit a request (rate-limit)")
}
continue
}
if err == ErrorUnauthorized {
break
}
return err
}
forceTokenUpdate = true
repeatAllCnt++
if repeatAllCnt > 3 {
return errors.New("Unable to submit a request (authorization failed)")
}
}
}