-
Notifications
You must be signed in to change notification settings - Fork 6
/
airtable.go
585 lines (517 loc) · 15.8 KB
/
airtable.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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
// Package airtable provides a high-level client to the Airtable API
// that allows the consumer to drop to a low-level request client when
// needed.
package airtable
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"path"
"reflect"
"strings"
"time"
"go.uber.org/ratelimit"
)
var (
DefaultRootURL = "https://api.airtable.com"
DefaultVersion = "v0"
DefaultHTTPClient = http.DefaultClient
DefaultLimiter = RateLimiter(5) // per second
)
// RateLimiter makes a new rate limiter using n as the number of
// requests per second that is allowed. If 0 is passed, the limiter will
// be unlimited.
func RateLimiter(n int) ratelimit.Limiter {
if n == 0 {
return ratelimit.NewUnlimited()
}
return ratelimit.New(n)
}
// QueryEncoder encodes options to a query string.
type QueryEncoder interface {
Encode() string
}
// Client represents an interface to communicate with the Airtable API.
//
// - APIKey: api key to use for each request. Requests will panic
// if this is not set.
//
// - BaseID: base this client will operate against. Requests will panic
// if this not set.
//
// - Version: version of the API to use.
//
// - RootURL: root URL to use.
//
// - HTTPClient: http.Client instance to use.
// http.DefaultClient
//
// - Limit: max requests to make per second.
type Client struct {
APIKey string
BaseID string
Version string
RootURL string
HTTPClient *http.Client
Limiter ratelimit.Limiter
}
// Request makes an HTTP request to the Airtable API without a body. See
// RequestWithBody for documentation.
func (c *Client) Request(
method string,
endpoint string,
options QueryEncoder,
) ([]byte, error) {
return c.RequestWithBody(method, endpoint, options, http.NoBody)
}
// ErrClientRequest is returned when the client runs into
// problems making a request.
type ErrClientRequest struct {
Err error
Method string
URL string
}
func (e ErrClientRequest) Error() string {
return fmt.Sprintf("airtable client request error: %s %s: %s", e.Method, e.URL, e.Err)
}
// RequestWithBody makes an HTTP request to the Airtable API. endpoint
// will be combined with the client's RootlURL, Version and BaseID, to
// create the complete URL. endpoint is expected to already be encoded;
// if necessary, use url.PathEscape before passing RequestWithBody.
//
// If client is missing APIKey or BaseID, this method will panic.
func (c *Client) RequestWithBody(
method string,
endpoint string,
options QueryEncoder,
body io.Reader,
) ([]byte, error) {
var err error
// finish setup or panic if the client isn't configured correctly
c.checkSetup()
if options == nil {
options = url.Values{}
}
url := c.makeURL(endpoint, options)
req, err := http.NewRequest(method, url, body)
if err != nil {
return nil, ErrClientRequest{
Err: err,
URL: url,
Method: method,
}
}
c.makeHeader(req)
// Take() will block until we can safely make the next request
// without going over the rate limit
c.Limiter.Take()
resp, err := c.HTTPClient.Do(req)
if err != nil {
return nil, ErrClientRequest{
Err: err,
URL: url,
Method: method,
}
}
bytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, ErrClientRequest{
Err: err,
URL: url,
Method: method,
}
}
if err = checkErrorResponse(bytes); err != nil {
return bytes, ErrClientRequest{
Err: err,
URL: url,
Method: method,
}
}
return bytes, nil
}
// Table returns a new Table that will use this client and operate
// against the table with the passed in name
func (c *Client) Table(name string) Table {
return Table{
client: c,
name: name,
}
}
func (c *Client) makeHeader(r *http.Request) {
r.Header = http.Header{}
r.Header.Add("Authorization", fmt.Sprintf("Bearer %s", c.APIKey))
r.Header.Add("Content-Type", "application/json")
}
func (c *Client) checkSetup() {
if c.BaseID == "" {
panic("airtable: Client missing BaseID")
}
if c.APIKey == "" {
panic("airtable: Client missing APIKey")
}
if c.HTTPClient == nil {
c.HTTPClient = DefaultHTTPClient
}
if c.Version == "" {
c.Version = DefaultVersion
}
if c.RootURL == "" {
c.RootURL = DefaultRootURL
}
if c.Limiter == nil {
c.Limiter = DefaultLimiter
}
}
func (c *Client) makeURL(resource string, options QueryEncoder) string {
q := options.Encode()
p := resource
uri := fmt.Sprintf("%s/%s/%s/%s?%s",
c.RootURL, c.Version, c.BaseID, p, q)
return uri
}
type genericErrorResponse struct {
Error interface{} `json:"error"`
}
func checkErrorResponse(b []byte) error {
var generic genericErrorResponse
if err := json.Unmarshal(b, &generic); err != nil {
return fmt.Errorf("couldn't unmarshal response: %s", err)
}
if generic.Error == nil {
return nil
}
return fmt.Errorf("%s", generic.Error)
}
// Record is a convenience struct for anonymous inclusion in
// user-constructed record structs.
type Record struct {
ID string
CreatedTime time.Time
}
// Fields is used in NewRecord for constructing new records.
type Fields map[string]interface{}
// NewRecord is a convenience method for applying a map of fields to a
// record container when the Fields struct is anonymous.
func NewRecord(recordPtr interface{}, data Fields) {
// panic if the recordPtr doesn't point to a record.
validateRecordArg(recordPtr)
// iterating over the container fields and applying those keys to
// the passed in fields would be "safer", but it could possibly
// mask user error if data is the complete wrong fit. instead we
// can iterate over data and apply that to the container, and fail
// early if there isn't a matching field.
ref := reflect.ValueOf(recordPtr).Elem()
typ := ref.Type()
fields := ref.FieldByName("Fields")
for k, v := range data {
f := fields.FieldByName(k)
val := reflect.ValueOf(v)
if !f.IsValid() {
errstr := fmt.Sprintf("airtable.NewRecord: cannot find field %s.%s", typ, k)
panic(errstr)
}
if fkind, vkind := f.Kind(), val.Kind(); fkind != vkind {
errstr := fmt.Sprintf("airtable.NewRecord: type error setting %s.%s: %s != %s", typ, k, fkind, vkind)
panic(errstr)
}
f.Set(val)
}
}
type deleteResponse struct {
Deleted bool
ID string
}
// Table represents an table in a base and provides methods for
// interacting with records in the table.
type Table struct {
name string
client *Client
}
// Get looks up a record from the table by ID and stores in in the
// object pointed to by recordPtr.
func (t *Table) Get(id string, recordPtr interface{}) error {
bytes, err := t.client.Request("GET", t.makePath(id), nil)
if err != nil {
return err
}
return json.Unmarshal(bytes, recordPtr)
}
func validateRecordArg(recordPtr interface{}) {
// must be:
// ... a pointer
typ := reflect.TypeOf(recordPtr)
recordPtrKind := typ.Kind()
if recordPtrKind != reflect.Ptr {
panic(fmt.Errorf("airtable type error: recordPtr must be a pointer, got %s", recordPtrKind))
}
// ... to a struct
record := typ.Elem()
recordKind := record.Kind()
if recordKind != reflect.Struct {
panic(fmt.Errorf("airtable type error: recordPtr must point to a struct, got %s", recordKind))
}
// ... which has a field named "Fields" that's a struct
fields, ok := record.FieldByName("Fields")
if !ok {
panic(fmt.Errorf("airtable type error: recordPtr must point to a struct with field 'Fields'"))
}
fieldsKind := fields.Type.Kind()
if fieldsKind != reflect.Struct {
panic(fmt.Errorf("airtable type error: recordPtr must point to a struct with field 'Fields' that is a struct, got %s", fieldsKind))
}
// ... an optional field named "Typecast" that's a bool
typecast, ok := record.FieldByName("Typecast")
if ok {
typecastKind := typecast.Type.Kind()
if typecastKind != reflect.Bool {
panic(fmt.Errorf("airtable type error: recordPtr must point to a struct with field 'Typecast' that is a bool, got %s", typecastKind))
}
}
// ... and a field named "ID" that's a string
id, ok := record.FieldByName("ID")
if !ok {
panic(fmt.Errorf("airtable type error: recordPtr must point to a struct with field 'ID'"))
}
idKind := id.Type.Kind()
if idKind != reflect.String {
panic(fmt.Errorf("airtable type error: recordPtr must point to a struct with field 'ID' that is a string, got %s", idKind))
}
}
// Update sends the updated record pointed to by recordPtr to the table
func (t *Table) Update(recordPtr interface{}) error {
// panic if the recordPtr doesn't point to a record.
validateRecordArg(recordPtr)
id := getID(recordPtr)
// panic makeJSONBody errors because it's an upstream programming
// error that needs to be fixed, not a user input error or a network
// condition.
body, err := makeJSONBody(recordPtr)
if err != nil {
panic(fmt.Errorf("airtable.Table#Update: unable to create JSON (%s)", err))
}
_, err = t.client.RequestWithBody("PATCH", t.makePath(id), Options{}, body)
if err != nil {
return err
}
return nil
}
// Create makes a new record in the table using the record pointed to by
// recordPtr. On success, updates the ID and CreatedTime of the object
// pointed to by recordPtr.
//
// recordPtr MUST have a Fields field that is a struct that can be
// marshaled to JSON or this method will panic.
func (t *Table) Create(recordPtr interface{}) error {
// panic if the recordPtr doesn't point to a record.
validateRecordArg(recordPtr)
body, err := makeJSONBody(recordPtr)
// panic if we can't create the JSON because it's an upstream
// programming error that needs to be fixed, not a user input error
// or a network condition.
if err != nil {
panic(fmt.Errorf("airtable.Table#Create: unable to create JSON (%s)", err))
}
res, err := t.client.RequestWithBody("POST", t.makePath(""), Options{}, body)
if err != nil {
return err
}
return json.Unmarshal(res, recordPtr)
}
// Delete removes a record from the table. On success, ID and
// CreatedTime of the object pointed to by recordPtr are removed.
func (t *Table) Delete(recordPtr interface{}) error {
// panic if the recordPtr doesn't point to a record.
validateRecordArg(recordPtr)
id := getID(recordPtr)
res, err := t.client.Request("DELETE", t.makePath(id), Options{})
if err != nil {
return fmt.Errorf("airtable.Table#Delete: request error %s", err)
}
deleted := deleteResponse{}
if err := json.Unmarshal(res, &deleted); err != nil {
return fmt.Errorf("airtable.Table#Delete: could not unpack request %s", err)
}
if !deleted.Deleted {
return fmt.Errorf("airtable.Table#Delete: did not delete, %s", res)
}
markAsDeleted(recordPtr)
return nil
}
// makeResponseContainer returns a new struct based on listPtr that can
// contain the response from a list query to an airtable. For example:
//
// type BookRecord struct {
// airtable.Record
// Fields struct {
// Title string
// Author string
// }
// }
// listPtr := &[]BookRecord{}
//
// Passing the above listPtr to makeResponseContainer will dynamically
// create a struct that looks like this:
//
// struct {
// Records []BookRecord
// Offset string
// }
func makeResponseContainer(listPtr interface{}) reflect.Value {
responseType := reflect.StructOf([]reflect.StructField{
{Name: "Records", Type: reflect.TypeOf(listPtr).Elem()},
{Name: "Offset", Type: reflect.TypeOf("string")},
})
return reflect.New(responseType)
}
func getOffset(listResponseContainer reflect.Value) string {
return listResponseContainer.Elem().FieldByName("Offset").String()
}
func appendRecordsToList(listPtr interface{}, results reflect.Value) {
var (
original = reflect.ValueOf(listPtr).Elem()
records = results.Elem().FieldByName("Records")
updated = reflect.AppendSlice(original, records)
)
original.Set(updated)
}
// getRecordType will get the base element type from a pointer to a
// slice. For example: getRecordType(*[]string) -> string
func getRecordType(ps interface{}) reflect.Type {
return reflect.TypeOf(ps).Elem().Elem()
}
func validateListArg(listPtr interface{}) {
// must be:
// ... a pointer
typ := reflect.TypeOf(listPtr)
listPtrKind := typ.Kind()
if listPtrKind != reflect.Ptr {
panic(fmt.Errorf("airtable type error: listPtr must be a pointer, got %s", listPtrKind))
}
// ... to a slice
list := typ.Elem()
listKind := list.Kind()
if listKind != reflect.Slice {
panic(fmt.Errorf("airtable type error: listPtr must point to a slice, got %s", listKind))
}
// ... whose elements are structs
elem := list.Elem()
elemKind := elem.Kind()
if elemKind != reflect.Struct {
panic(fmt.Errorf("airtable type error: listPtr must point to a slice of structs, got %s", elemKind))
}
// ... the structs have a field named "Fields" that's a struct
fields, ok := elem.FieldByName("Fields")
if !ok {
panic(fmt.Errorf("airtable type error: listPtr must point to a slice of structs with field 'Fields'"))
}
fieldsKind := fields.Type.Kind()
if fieldsKind != reflect.Struct {
panic(fmt.Errorf("airtable type error: listPtr must point to a slice of structs with field 'Fields' that is a struct, got %s", fieldsKind))
}
// ... and a field named "ID" that's a string
id, ok := elem.FieldByName("ID")
if !ok {
panic(fmt.Errorf("airtable type error: listPtr must point to a slice of structs with field 'ID'"))
}
idKind := id.Type.Kind()
if idKind != reflect.String {
panic(fmt.Errorf("airtable type error: listPtr must point to a slice of structs with field 'ID' that is a string, got %s", idKind))
}
}
// List queries the table for list of records and stores it in the
// object pointed to by listPtr. By default, List will recurse to get
// all of the records until there are no more left to get, but this can
// be overriden by using the MaxRecords option. See Options for a
// complete list of the options that are supported.
//
// listPtr must be a pointer to a slice of records, which are structs
// that contain, at a minimum, `ID string` and `Fields struct {...}`
// fields. For example:
//
// type BookRecord struct {
// airtable.Record // provides ID and CreatedTime
// Fields struct {
// Title string
// Author string
// }
// }
// listPtr := &[]BookRecord{}
//
// This will be validated and cause a panic at runtime if listPtr is the
// wrong type.
func (t *Table) List(listPtr interface{}, options *Options) error {
validateListArg(listPtr)
if options == nil {
options = &Options{}
}
// for "sort" and "fields" we need to have access to the type of
// record so we can look up the JSON names of the fields.
options.setType(getRecordType(listPtr))
for {
container := makeResponseContainer(listPtr)
bytes, err := t.client.Request("GET", t.makePath(""), options)
if err != nil {
return err
}
err = json.Unmarshal(bytes, container.Interface())
if err != nil {
return err
}
appendRecordsToList(listPtr, container)
options.offset = getOffset(container)
if options.offset == "" {
break
}
}
return nil
}
func (t *Table) makePath(id string) string {
name := url.PathEscape(t.name)
if id == "" {
return name
}
return path.Join(name, id)
}
func markAsDeleted(recordPtr interface{}) {
var (
record = reflect.ValueOf(recordPtr).Elem()
zeroTime = reflect.ValueOf(time.Time{})
id = record.FieldByName("ID")
created = record.FieldByName("CreatedTime")
)
if id.IsValid() {
id.SetString("")
}
if created.IsValid() {
created.Set(zeroTime)
}
}
// makeJSONBody returns an io.Reader prepared for use in either Create
// or Update operations.
func makeJSONBody(recordPtr interface{}) (io.Reader, error) {
f := getFields(recordPtr)
b, err := json.Marshal(f)
if err != nil {
return nil, err
}
t := getTypecast(recordPtr)
jsonstr := fmt.Sprintf(`{"fields": %s, "typecast": %t}`, b, t)
body := strings.NewReader(jsonstr)
return body, nil
}
func getFields(ptr interface{}) interface{} {
return reflect.ValueOf(ptr).Elem().FieldByName("Fields").Interface()
}
func getTypecast(ptr interface{}) interface{} {
if reflect.ValueOf(ptr).Elem().FieldByName("Typecast").IsValid() {
return reflect.ValueOf(ptr).Elem().FieldByName("Typecast").Interface()
}
return false
}
func getID(ptr interface{}) string {
return reflect.ValueOf(ptr).Elem().FieldByName("ID").String()
}