-
Notifications
You must be signed in to change notification settings - Fork 80
/
client.go
231 lines (196 loc) · 5.23 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
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
226
227
228
229
230
231
package notionapi
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"reflect"
"strconv"
"time"
)
const (
apiURL = "https://api.notion.com"
apiVersion = "v1"
notionVersion = "2022-06-28"
maxRetries = 3
)
type Token string
type errJsonDecodeFunc func(data []byte) error
func (it Token) String() string {
return string(it)
}
// ClientOption to configure API client
type ClientOption func(*Client)
type Client struct {
httpClient *http.Client
baseUrl *url.URL
apiVersion string
notionVersion string
maxRetries int
Token Token
// used in Authorization header only for requests that require Basic authentication.
oauthID string
oauthSecret string
Database DatabaseService
Block BlockService
Page PageService
User UserService
Search SearchService
Comment CommentService
Authentication AuthenticationService
}
func NewClient(token Token, opts ...ClientOption) *Client {
u, err := url.Parse(apiURL)
if err != nil {
panic(err)
}
c := &Client{
httpClient: http.DefaultClient,
Token: token,
baseUrl: u,
apiVersion: apiVersion,
notionVersion: notionVersion,
maxRetries: maxRetries,
}
c.Database = &DatabaseClient{apiClient: c}
c.Block = &BlockClient{apiClient: c}
c.Page = &PageClient{apiClient: c}
c.User = &UserClient{apiClient: c}
c.Search = &SearchClient{apiClient: c}
c.Comment = &CommentClient{apiClient: c}
c.Authentication = &AuthenticationClient{apiClient: c}
for _, opt := range opts {
opt(c)
}
return c
}
// WithHTTPClient overrides the default http.Client
func WithHTTPClient(client *http.Client) ClientOption {
return func(c *Client) {
c.httpClient = client
}
}
// WithVersion overrides the Notion API version
func WithVersion(version string) ClientOption {
return func(c *Client) {
c.notionVersion = version
}
}
// WithRetry overrides the default number of max retry attempts on 429 errors
func WithRetry(retries int) ClientOption {
return func(c *Client) {
c.maxRetries = retries
}
}
// WithOAuthAppCredentials sets the OAuth app ID and secret to use when fetching a token from Notion.
func WithOAuthAppCredentials(id, secret string) ClientOption {
return func(c *Client) {
c.oauthID = id
c.oauthSecret = secret
}
}
func (c *Client) request(ctx context.Context, method string, urlStr string, queryParams map[string]string, requestBody interface{}) (*http.Response, error) {
return c.requestImpl(ctx, method, urlStr, queryParams, requestBody, false, decodeClientError)
}
func (c *Client) requestImpl(ctx context.Context, method string, urlStr string, queryParams map[string]string, requestBody interface{}, basicAuth bool, errDecoder errJsonDecodeFunc) (*http.Response, error) {
u, err := c.baseUrl.Parse(fmt.Sprintf("%s/%s", c.apiVersion, urlStr))
if err != nil {
return nil, err
}
var buf io.ReadWriter
if requestBody != nil && !reflect.ValueOf(requestBody).IsNil() {
body, err := json.Marshal(requestBody)
if err != nil {
return nil, err
}
buf = bytes.NewBuffer(body)
}
if len(queryParams) > 0 {
q := u.Query()
for k, v := range queryParams {
q.Add(k, v)
}
u.RawQuery = q.Encode()
}
req, err := http.NewRequest(method, u.String(), buf)
if err != nil {
return nil, err
}
if basicAuth {
cred := base64.StdEncoding.EncodeToString([]byte(c.oauthID + ":" + c.oauthSecret))
req.Header.Add("Authorization", fmt.Sprintf("Basic %s", cred))
} else {
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", c.Token.String()))
}
req.Header.Add("Notion-Version", c.notionVersion)
req.Header.Add("Content-Type", "application/json")
failedAttempts := 0
var res *http.Response
for {
var err error
res, err = c.httpClient.Do(req.WithContext(ctx))
if err != nil {
return nil, err
}
if res.StatusCode != http.StatusTooManyRequests {
break
}
failedAttempts++
if failedAttempts == c.maxRetries {
return nil, &RateLimitedError{Message: fmt.Sprintf("Retry request with 429 response failed after %d retries", failedAttempts)}
}
// https://developers.notion.com/reference/request-limits#rate-limits
retryAfterHeader := res.Header["Retry-After"]
if len(retryAfterHeader) == 0 {
return nil, &RateLimitedError{Message: "Retry-After header missing from Notion API response headers for 429 response"}
}
retryAfter := retryAfterHeader[0]
waitSeconds, err := strconv.Atoi(retryAfter)
if err != nil {
break // should not happen
}
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(time.Duration(waitSeconds) * time.Second):
}
}
if res.StatusCode != http.StatusOK {
data, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
return nil, errDecoder(data)
}
return res, nil
}
func decodeClientError(data []byte) error {
var apiErr Error
err := json.Unmarshal(data, &apiErr)
if err != nil {
return err
}
return &apiErr
}
type Pagination struct {
StartCursor Cursor
PageSize int
}
func (p *Pagination) ToQuery() map[string]string {
if p == nil {
return nil
}
r := map[string]string{}
if p.StartCursor != "" {
r["start_cursor"] = p.StartCursor.String()
}
if p.PageSize != 0 {
r["page_size"] = strconv.Itoa(p.PageSize)
}
return r
}