-
Notifications
You must be signed in to change notification settings - Fork 2
/
client.go
181 lines (150 loc) · 4.19 KB
/
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
package expensify
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"net/url"
"strings"
"time"
)
const (
baseURL = "https://integrations.expensify.com/Integration-Server/ExpensifyIntegrations"
version = "0.1.0"
)
var defaultHTTPClient = &http.Client{
Transport: &http.Transport{
DialContext: (&net.Dialer{
Timeout: 5 * time.Second,
}).DialContext,
TLSHandshakeTimeout: 5 * time.Second,
},
}
// Error is the generic error response returned on non 2xx HTTP status codes.
type Error struct {
Message string `json:"responseMessage"`
StatusCode int `json:"responseCode"`
}
// Error implements the error interface.
func (e Error) Error() string {
return fmt.Sprintf("%s: %s", http.StatusText(e.StatusCode), e.Message)
}
// An Option can be used to configure the behaviour of the API client.
type Option func(c *Client) error
// SetClient specifies a custom http client that should be used to make
// requests.
func SetClient(client *http.Client) Option {
return func(c *Client) error {
if client == nil {
return nil
}
c.httpClient = client
return nil
}
}
// Client provides the Expensify HTTP API operations.
type Client struct {
baseURL *url.URL
userAgent string
partnerUserID string
partnerUserSecret string
httpClient *http.Client
Expense ExpenseService
}
// NewClient returns a new Expensify API client. The credentials can be
// retrieved from https://www.expensify.com/tools/integrations.
func NewClient(partnerUserID, partnerUserSecret string, options ...Option) (*Client, error) {
u, err := url.ParseRequestURI(baseURL)
if err != nil {
return nil, err
}
c := &Client{
baseURL: u,
userAgent: fmt.Sprintf("expensify-go/%s", version),
partnerUserID: partnerUserID,
partnerUserSecret: partnerUserSecret,
httpClient: defaultHTTPClient,
}
c.Expense = &expenseService{c}
// Apply supplied options.
if err := c.Options(options...); err != nil {
return nil, err
}
return c, nil
}
// Options applies Options to a client instance.
func (c *Client) Options(options ...Option) error {
for _, option := range options {
if err := option(c); err != nil {
return err
}
}
return nil
}
// call creates a new API request and executes it.
func (c *Client) call(ctx context.Context, jobType, inputType string, payload, v interface{}) error {
req, err := c.newRequest(ctx, jobType, inputType, payload)
if err != nil {
return err
}
return c.do(req, v)
}
// newRequest creates an API request. If specified, the value pointed to by
// body will be included as the request body.
func (c *Client) newRequest(ctx context.Context, jobType, inputType string, payload interface{}) (*http.Request, error) {
job := &jobRequest{
Type: jobType,
InputSettings: &inputSettings{
Type: inputType,
data: payload,
},
}
job.Credentials.PartnerUserID = c.partnerUserID
job.Credentials.PartnerUserSecret = c.partnerUserSecret
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(job); err != nil {
return nil, err
}
form := url.Values{}
form.Add("requestJobDescription", buf.String())
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL.String(), strings.NewReader(form.Encode()))
if err != nil {
return nil, err
}
// Set headers.
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Accept", "application/json")
req.Header.Set("User-Agent", c.userAgent)
return req, nil
}
// do sends an API request and returns the API response.
func (c *Client) do(req *http.Request, v interface{}) error {
resp, err := c.httpClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
// The Expensify API is super shitty and doesn't return proper HTTP status
// codes (200 all the way). So we need to decode the body and see if it's an
// error. If not, we need to decode it again into the proper response
// struct.
var (
buf bytes.Buffer
r = io.TeeReader(resp.Body, &buf)
)
var errResp Error
if err = json.NewDecoder(r).Decode(&errResp); err != nil {
return err
} else if code := errResp.StatusCode; code != 0 && code != http.StatusOK {
return errResp
}
if v != nil {
if err = json.NewDecoder(&buf).Decode(v); err != nil {
return err
}
}
return nil
}