This repository has been archived by the owner on Sep 21, 2023. It is now read-only.
forked from bennylope/go-harvest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
api_client.go
210 lines (180 loc) · 5.24 KB
/
api_client.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
/*
Package harvest provides data structures and a wrapper for the Harvest API
*/
package harvest
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"os"
"strings"
"sync"
"time"
"golang.org/x/sync/singleflight"
)
// APIClient contains credentials & data interfaces
type APIClient struct {
// Authentication and connection information
username string
password string
subdomain string
httpClient *http.Client
// caching
cacheGroup *singleflight.Group
cacheInterval time.Duration
cacheEntries map[string]cacheEntry // url -> response data
cacheMut sync.Mutex
// Data interface accessors
Client *ClientService
People *PersonService
Project *ProjectService
Invoice *InvoiceService
Account *AccountService
Task *TaskService
TaskAssignment *TaskAssignmentService
Contact *ContactService
Expense *ExpenseService
ExpenseCategory *ExpenseCategoryService
Entry *EntryService
Payment *PaymentService
}
type cacheEntry struct {
when time.Time
data []byte
}
// newAPIClient instantiates a new http.Client and returns a new APIClient
func newAPIClient(subdomain string, httpClient *http.Client, cacheInterval time.Duration) (c *APIClient) {
c = new(APIClient)
c.subdomain = subdomain
c.cacheGroup = new(singleflight.Group)
c.cacheInterval = cacheInterval
c.cacheEntries = make(map[string]cacheEntry)
if httpClient != nil {
c.httpClient = httpClient
} else {
c.httpClient = new(http.Client)
}
c.Client = &ClientService{Service{c}}
c.People = &PersonService{Service{c}}
c.Project = &ProjectService{Service{c}}
c.Invoice = &InvoiceService{Service{c}}
c.Account = &AccountService{Service{c}}
c.Task = &TaskService{Service{c}}
c.TaskAssignment = &TaskAssignmentService{Service{c}}
c.Contact = &ContactService{Service{c}}
c.Expense = &ExpenseService{Service{c}}
c.ExpenseCategory = &ExpenseCategoryService{Service{c}}
c.Entry = &EntryService{Service{c}}
c.Payment = &PaymentService{Service{c}}
return c
}
// NewAPIClientWithBasicAuth instantiates a new http.Client and returns a new
// APIClient using HTTP basic auth credentials
func NewAPIClientWithBasicAuth(username, password, subdomain string) (c *APIClient) {
return NewCachingAPIClientWithBasicAuth(username, password, subdomain, 0)
}
// NewCachingAPIClientWithBasicAuth instantiates a new http.Client and
// returns a new APIClient using HTTP basic auth credentials. Responses are
// cached and reused for up to cacheInterval.
func NewCachingAPIClientWithBasicAuth(username, password, subdomain string, cacheInterval time.Duration) (c *APIClient) {
var missingData []string
if subdomain == "" {
missingData = append(missingData, "subdomain")
}
if username == "" {
missingData = append(missingData, "username")
}
if password == "" {
missingData = append(missingData, "password")
}
errorMsg := strings.Join(missingData, ", ")
if errorMsg != "" {
fmt.Println("ERROR! You are missing the following:", errorMsg)
os.Exit(1)
}
c = newAPIClient(subdomain, nil, cacheInterval)
c.username = username
c.password = password
return c
}
// GetJSON makes an HTTP GET request to the specified path and returns the body
// of the HTTP response
func (c *APIClient) GetJSON(path string) (jsonResponse []byte, err error) {
v, err, _ := c.cacheGroup.Do(path, func() (interface{}, error) {
c.cacheMut.Lock()
cur := c.cacheEntries[path]
c.cacheMut.Unlock()
if time.Since(cur.when) < c.cacheInterval {
return cur.data, nil
}
data, err := c.uncachedGetJSON(path)
if err != nil {
return nil, err
}
c.cacheMut.Lock()
c.cacheEntries[path] = cacheEntry{
when: time.Now(),
data: data,
}
c.cacheMut.Unlock()
return data, nil
})
if err != nil {
return nil, err
}
return v.([]byte), nil
}
func (c *APIClient) uncachedGetJSON(path string) (jsonResponse []byte, err error) {
resourceURL := fmt.Sprintf("https://%v.harvestapp.com%v", c.subdomain, path)
request, err := http.NewRequest(http.MethodGet, resourceURL, nil)
if err != nil {
return nil, err
}
request.SetBasicAuth(c.username, c.password)
resp, err := c.httpClient.Do(request)
if err != nil {
return nil, err
}
defer resp.Body.Close()
bs, err := ioutil.ReadAll(resp.Body)
if err != nil {
return bs, err
}
if resp.StatusCode != http.StatusOK {
return bs, errors.New(resp.Status)
}
return bs, nil
}
func (c *APIClient) PostJSON(path string, v interface{}) error {
return c.doJSON(http.MethodPost, path, v)
}
func (c *APIClient) PutJSON(path string, v interface{}) error {
return c.doJSON(http.MethodPut, path, v)
}
func (c *APIClient) doJSON(method string, path string, v interface{}) error {
bs, err := json.Marshal(v)
if err != nil {
return err
}
r := bytes.NewReader(bs)
resourceURL := fmt.Sprintf("https://%v.harvestapp.com%v", c.subdomain, path)
request, err := http.NewRequest(method, resourceURL, r)
if err != nil {
return err
}
request.Header.Set("Content-Type", "application/json")
request.SetBasicAuth(c.username, c.password)
resp, err := c.httpClient.Do(request)
if err != nil {
return err
}
ioutil.ReadAll(resp.Body)
resp.Body.Close()
if resp.StatusCode != http.StatusCreated && resp.StatusCode != http.StatusOK {
return errors.New(resp.Status)
}
return nil
}