-
Notifications
You must be signed in to change notification settings - Fork 11
/
api.go
225 lines (189 loc) · 5.69 KB
/
api.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
package harvest
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"github.com/pkg/errors"
)
const CLIENT_VERSION = "1.0"
const HARVEST_DOMAIN = "api.harvestapp.com"
const HARVEST_API_VERSION = "v2"
type API struct {
client *http.Client
Logger logger
BaseURL string
AccountID string
AccessToken string
RefreshToken string
UserAgent string
}
type logger interface {
Debugf(string, ...interface{})
}
func NewTokenAPI(accountID string, accessToken string) *API {
a := API{}
a.client = http.DefaultClient
a.BaseURL = "https://" + HARVEST_DOMAIN + "/" + HARVEST_API_VERSION
a.AccountID = accountID
a.AccessToken = accessToken
return &a
}
func (a *API) GetPaginated(path string, args Arguments, target Pageable, afterFetch func()) error {
page := 1
args["page"] = fmt.Sprintf("%d", page)
err := a.Get(path, args, target)
if err != nil {
return err
}
afterFetch()
for target.HasNextPage() {
page++
args["page"] = fmt.Sprintf("%d", page)
err = a.Get(path, args, target)
if err != nil {
return err
}
afterFetch()
}
return nil
}
func (a *API) Get(path string, args Arguments, target interface{}) error {
url := fmt.Sprintf("%s%s", a.BaseURL, path)
urlWithParams := fmt.Sprintf("%s?%s", url, args.ToURLValues().Encode())
req, err := http.NewRequest("GET", urlWithParams, nil)
if err != nil {
return errors.Wrapf(err, "Invalid GET request %s", url)
}
a.AddHeaders(req)
resp, err := a.client.Do(req)
if err != nil {
return errors.Wrapf(err, "HTTP request failure on %s", url)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
var body []byte
body, err = ioutil.ReadAll(resp.Body)
return errors.Errorf("HTTP request failure on %s: %s %s", url, string(body), err)
}
decoder := json.NewDecoder(resp.Body)
err = decoder.Decode(target)
if err != nil {
body, _ := ioutil.ReadAll(resp.Body)
return errors.Wrapf(err, "JSON decode failed on %s: %s", url, string(body))
}
return nil
}
func (a *API) Put(path string, args Arguments, postData interface{}, target interface{}) error {
url := fmt.Sprintf("%s%s", a.BaseURL, path)
urlWithParams := fmt.Sprintf("%s?%s", url, args.ToURLValues().Encode())
buffer := new(bytes.Buffer)
if postData != nil {
json.NewEncoder(buffer).Encode(postData)
}
req, err := http.NewRequest("PUT", urlWithParams, buffer)
if err != nil {
return errors.Wrapf(err, "Invalid PUT request %s", url)
}
a.AddHeaders(req)
req.Header.Set("Content-Type", "application/json; charset=utf-8")
resp, err := a.client.Do(req)
if err != nil {
return errors.Wrapf(err, "HTTP request failure on %s", url)
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
var body []byte
body, err = ioutil.ReadAll(resp.Body)
return errors.Wrapf(err, "HTTP request failure on %s: %s %s", url, string(body), err)
}
// Harvest V1 API returns an empty response, with a Location header including the
// URI of the created object (e.g. /projects/254454)
redirectDestination := resp.Header.Get("Location")
if redirectDestination != "" {
return a.Get(redirectDestination, args, target)
} else {
decoder := json.NewDecoder(resp.Body)
err = decoder.Decode(target)
if err != nil {
body, _ := ioutil.ReadAll(resp.Body)
return errors.Wrapf(err, "JSON decode failed on %s: %s", url, string(body))
}
}
return nil
}
func (a *API) Post(path string, args Arguments, postData interface{}, target interface{}) error {
url := fmt.Sprintf("%s%s", a.BaseURL, path)
urlWithParams := fmt.Sprintf("%s?%s", url, args.ToURLValues().Encode())
buffer := new(bytes.Buffer)
if postData != nil {
json.NewEncoder(buffer).Encode(postData)
}
req, err := http.NewRequest("POST", urlWithParams, buffer)
if err != nil {
return errors.Wrapf(err, "Invalid POST request %s", url)
}
a.AddHeaders(req)
req.Header.Set("Content-Type", "application/json; charset=utf-8")
resp, err := a.client.Do(req)
if err != nil {
return errors.Wrapf(err, "HTTP request failure on %s", url)
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
var body []byte
body, err = ioutil.ReadAll(resp.Body)
return errors.Wrapf(err, "HTTP request failure on %s: %s %s", url, string(body), err)
}
decoder := json.NewDecoder(resp.Body)
err = decoder.Decode(target)
if err != nil {
body, _ := ioutil.ReadAll(resp.Body)
return errors.Wrapf(err, "JSON decode failed on POST to %s: %s", url, string(body))
}
return nil
}
func (a *API) Delete(path string, args Arguments) error {
url := fmt.Sprintf("%s%s", a.BaseURL, path)
urlWithParams := fmt.Sprintf("%s?%s", url, args.ToURLValues().Encode())
req, err := http.NewRequest("DELETE", urlWithParams, nil)
if err != nil {
return errors.Wrapf(err, "Invalid DELETE request %s", url)
}
a.AddHeaders(req)
resp, err := a.client.Do(req)
if err != nil {
return errors.Wrapf(err, "HTTP request failure on %s", url)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
var body []byte
body, err = ioutil.ReadAll(resp.Body)
return errors.Wrapf(err, "HTTP request failure on %s: %s %s", url, string(body), err)
}
return nil
}
// Applies relevant User-Agent, Accept, Authorization headers
func (a *API) AddHeaders(req *http.Request) {
req.Header.Set("Accept", "application/json")
if a.UserAgent != "" {
req.Header.Set("User-Agent", a.UserAgent)
} else {
req.Header.Set("User-Agent", defaultUserAgent())
}
if a.AccountID != "" {
req.Header.Set("Harvest-Account-Id", a.AccountID)
}
if a.AccessToken != "" {
req.Header.Set("Authorization", "Bearer "+a.AccessToken)
}
}
func (a *API) log(format string, args ...interface{}) {
if a.Logger != nil {
a.Logger.Debugf(format, args)
}
}
func defaultUserAgent() string {
return "github.com/adlio/harvest v" + CLIENT_VERSION
}