├── .gitignore ├── go.mod ├── Makefile ├── go.sum ├── example_new_record_test.go ├── example_package_test.go ├── fields.go ├── README.md ├── options.go ├── LICENSE └── airtable.go /.gitignore: -------------------------------------------------------------------------------- 1 | /.plan 2 | /bases.txt 3 | /secrets.env 4 | *.snapshot 5 | /testdata 6 | /coverage.out 7 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/brianloveswords/airtable 2 | 3 | go 1.13 4 | 5 | require ( 6 | github.com/stretchr/testify v1.4.0 // indirect 7 | go.uber.org/atomic v1.4.0 // indirect 8 | go.uber.org/ratelimit v0.1.0 9 | ) 10 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | test: 2 | go test -v ./... 3 | 4 | clean: 5 | rm -f testdata/* 6 | 7 | cover: 8 | go test -coverprofile=coverage.out 9 | 10 | cover-html: 11 | go test -coverprofile=coverage.out &&\ 12 | go tool cover -html=coverage.out 13 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= 2 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 3 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 4 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 5 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 6 | github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= 7 | github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= 8 | go.uber.org/atomic v1.4.0 h1:cxzIVoETapQEqDhQu3QfnvXAV4AlzcvUCxkVUFw3+EU= 9 | go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= 10 | go.uber.org/ratelimit v0.1.0 h1:U2AruXqeTb4Eh9sYQSTrMhH8Cb7M0Ian2ibBOnBcnAw= 11 | go.uber.org/ratelimit v0.1.0/go.mod h1:2X8KaoNd1J0lZV+PxJk/5+DGbO/tpwLR1m++a7FnB/Y= 12 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 13 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 14 | gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= 15 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 16 | -------------------------------------------------------------------------------- /example_new_record_test.go: -------------------------------------------------------------------------------- 1 | package airtable_test 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/brianloveswords/airtable" 7 | ) 8 | 9 | func ExampleNewRecord() { 10 | type BookRecord struct { 11 | airtable.Record 12 | Fields struct { 13 | Title string 14 | Author string 15 | Rating int 16 | Tags airtable.MultiSelect 17 | } 18 | } 19 | 20 | binti := &BookRecord{} 21 | airtable.NewRecord(binti, airtable.Fields{ 22 | "Title": "Binti", 23 | "Author": "Nnedi Okorafor", 24 | "Rating": 4, 25 | "Tags": airtable.MultiSelect{"sci-fi", "fantasy"}, 26 | }) 27 | 28 | fmt.Println(binti.Fields.Author) 29 | // Output: Nnedi Okorafor 30 | } 31 | func ExampleNewRecord_withoutNewRecord() { 32 | // You can avoid using NewRecord if you use a named struct instead 33 | // of an anonymous struct for the Fields field in record struct. 34 | 35 | type Book struct { 36 | Title string 37 | Author string 38 | Rating int 39 | Tags airtable.MultiSelect 40 | } 41 | 42 | type BookRecord struct { 43 | airtable.Record 44 | Fields Book 45 | } 46 | 47 | binti := &BookRecord{ 48 | Fields: Book{ 49 | Title: "Binti", 50 | Author: "Nnedi Okorafor", 51 | Rating: 4, 52 | Tags: airtable.MultiSelect{"sci-fi", "fantasy"}, 53 | }, 54 | } 55 | 56 | fmt.Println(binti.Fields.Author) 57 | // Output: Nnedi Okorafor 58 | } 59 | -------------------------------------------------------------------------------- /example_package_test.go: -------------------------------------------------------------------------------- 1 | package airtable_test 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | "time" 7 | 8 | "github.com/brianloveswords/airtable" 9 | ) 10 | 11 | type PublicDomainBookRecord struct { 12 | airtable.Record // provides ID, CreatedTime 13 | Fields struct { 14 | Title string `json:"Book Title"` 15 | Author string 16 | Publication time.Time `json:"Publication Date"` 17 | FullText string 18 | Rating int 19 | Tags airtable.MultiSelect 20 | } 21 | } 22 | 23 | // String shows the book record like " by <author> [<rating>]" 24 | func (r *PublicDomainBookRecord) String() string { 25 | f := r.Fields 26 | return fmt.Sprintf("%s by %s %s", f.Title, f.Author, r.Rating()) 27 | } 28 | 29 | // Rating outputs a rating like [***··] 30 | func (r *PublicDomainBookRecord) Rating() string { 31 | var ( 32 | max = 5 33 | rating = r.Fields.Rating 34 | stars = strings.Repeat("*", rating) 35 | dots = strings.Repeat("·", max-rating) 36 | ) 37 | return fmt.Sprintf("[%s%s]", stars, dots) 38 | } 39 | 40 | func Example() { 41 | // Create the Airtable client with your APIKey and BaseID for the 42 | // base you want to interact with. 43 | client := airtable.Client{ 44 | APIKey: "keyXXXXXXXXXXXXXX", 45 | BaseID: "appwNa5g4gHCVZQPm", 46 | } 47 | 48 | books := client.Table("Public Domain Books") 49 | 50 | bestBooks := []PublicDomainBookRecord{} 51 | books.List(&bestBooks, &airtable.Options{ 52 | // The whole response would be huge because of FullText so we 53 | // should just get the title and author. NOTE: even though the 54 | // field is called "Book Title" in the JSON, we should use field 55 | // by the name we defined it in our struct. 56 | Fields: []string{"Title", "Author", "Rating"}, 57 | 58 | // Only get books with a rating that's 4 or higher. 59 | Filter: `{Rating} >= 4`, 60 | 61 | // Let's sort from highest to lowest rating, then by author 62 | Sort: airtable.Sort{ 63 | {"Rating", airtable.SortDesc}, 64 | {"Author", airtable.SortAsc}, 65 | }, 66 | }) 67 | 68 | fmt.Println("Best Public Domain Books:") 69 | for _, bookRecord := range bestBooks { 70 | fmt.Println(bookRecord.String()) 71 | } 72 | 73 | // Let's prune our library of books we aren't super into. 74 | badBooks := []PublicDomainBookRecord{} 75 | books.List(&badBooks, &airtable.Options{ 76 | Fields: []string{"Title", "Author", "Rating"}, 77 | Filter: `{Rating} < 3`, 78 | }) 79 | for _, badBook := range badBooks { 80 | fmt.Println("deleting", badBook) 81 | books.Delete(&badBook) 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /fields.go: -------------------------------------------------------------------------------- 1 | package airtable 2 | 3 | import ( 4 | "encoding/json" 5 | "log" 6 | ) 7 | 8 | // Attachment type. When creating a new attachment, only URL and 9 | // optionally Filename should be provided. 10 | type Attachment []struct { 11 | ID string 12 | URL string `json:"url"` 13 | Filename string `json:"filename"` 14 | Size float64 15 | Type string 16 | Thumbnails struct { 17 | Small AttachmentThumbnail 18 | Large AttachmentThumbnail 19 | } 20 | } 21 | 22 | // AttachmentThumbnail holds the details of an individual thumbnail 23 | type AttachmentThumbnail struct { 24 | URL string 25 | Width float64 26 | Height float64 27 | } 28 | 29 | // TODO: make MultiSelect more useful. It's a natural fit for a Set 30 | // type, but we don't have sets out of the box and it currently seems 31 | // frivolous to pull in an external dependency or even make a naive set 32 | // type just for this. 33 | 34 | // MultiSelect type. Alias for string slice. 35 | type MultiSelect []string 36 | 37 | // TODO: make RecordLink more useful. For example, if we know what table 38 | // the record links are supposed to come from, we could automatically 39 | // hydrate those links instead of returning strings. We could also 40 | // automatically create new records when necessary if the linked record 41 | // object is novel in a Create operation. 42 | 43 | // RecordLink type. Alias for string slice. 44 | type RecordLink []string 45 | 46 | // FormulaResult can be a string, number or error. 47 | type FormulaResult struct { 48 | Number *float64 49 | String *string 50 | Error *string 51 | } 52 | 53 | // UnmarshalJSON tries to figure out if this is an error, a string or 54 | // a number. 55 | func (f *FormulaResult) UnmarshalJSON(b []byte) error { 56 | i := new(interface{}) 57 | if err := json.Unmarshal(b, &i); err != nil { 58 | return err 59 | } 60 | switch v := (*i).(type) { 61 | case string: 62 | f.String = &v 63 | case float64: 64 | f.Number = &v 65 | case map[string]interface{}: 66 | err, ok := v["error"].(string) 67 | if !ok { 68 | panic("parse error") 69 | } 70 | f.Error = &err 71 | default: 72 | log.Fatal("couldn't parse Formula type as number, string or error") 73 | } 74 | return nil 75 | } 76 | 77 | // Value returns the underlying value if the formula results is a 78 | // string or a number, otherwise return nil pointer and false 79 | func (f *FormulaResult) Value() (v interface{}, ok bool) { 80 | if f.Error != nil { 81 | return nil, false 82 | } 83 | if f.String != nil { 84 | return *f.String, true 85 | } 86 | return *f.Number, true 87 | } 88 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # airtable 2 | Go package for interacting with the Airtable API. 3 | 4 | ## License 5 | 6 | [Mozilla Public License 2.0](https://www.mozilla.org/en-US/MPL/2.0/) 7 | 8 | ## Install 9 | 10 | ``` shell 11 | $ go get github.com/brianloveswords/airtable 12 | ``` 13 | 14 | ## API Documentation 15 | See [airtable package documentation on godoc.org](https://godoc.org/github.com/brianloveswords/airtable) 16 | 17 | ## Example Usage 18 | ``` go 19 | package main 20 | 21 | import ( 22 | "fmt" 23 | "strings" 24 | "time" 25 | 26 | "github.com/brianloveswords/airtable" 27 | ) 28 | 29 | type PublicDomainBookRecord struct { 30 | airtable.Record // provides ID, CreatedTime 31 | Fields struct { 32 | Title string `json:"Book Title"` 33 | Author string 34 | Publication time.Time `json:"Publication Date"` 35 | FullText string 36 | Rating int 37 | Tags airtable.MultiSelect 38 | } 39 | } 40 | 41 | // String shows the book record like "<title> by <author> [<rating>]" 42 | func (r *PublicDomainBookRecord) String() string { 43 | f := r.Fields 44 | return fmt.Sprintf("%s by %s %s", f.Title, f.Author, r.Rating()) 45 | } 46 | 47 | // Rating outputs a rating like [***··] 48 | func (r *PublicDomainBookRecord) Rating() string { 49 | var ( 50 | max = 5 51 | rating = r.Fields.Rating 52 | stars = strings.Repeat("*", rating) 53 | dots = strings.Repeat("·", max-rating) 54 | ) 55 | return fmt.Sprintf("[%s%s]", stars, dots) 56 | } 57 | 58 | func Example() { 59 | // Create the Airtable client with your APIKey and BaseID for the 60 | // base you want to interact with. 61 | client := airtable.Client{ 62 | APIKey: "keyXXXXXXXXXXXXXX", 63 | BaseID: "appwNa5g4gHCVZQPm", 64 | } 65 | 66 | books := client.Table("Public Domain Books") 67 | 68 | bestBooks := []PublicDomainBookRecord{} 69 | books.List(&bestBooks, &airtable.Options{ 70 | // The whole response would be huge because of FullText so we 71 | // should just get the title and author. NOTE: even though the 72 | // field is called "Book Title" in the JSON, we should use field 73 | // by the name we defined it in our struct. 74 | Fields: []string{"Title", "Author", "Rating"}, 75 | 76 | // Only get books with a rating that's 4 or higher. 77 | Filter: `{Rating} >= 4`, 78 | 79 | // Let's sort from highest to lowest rating, then by author 80 | Sort: airtable.Sort{ 81 | {"Rating", airtable.SortDesc}, 82 | {"Author", airtable.SortAsc}, 83 | }, 84 | }) 85 | 86 | fmt.Println("Best Public Domain Books:") 87 | for _, bookRecord := range bestBooks { 88 | fmt.Println(bookRecord.String()) 89 | } 90 | 91 | // Let's prune our library of books we aren't super into. 92 | badBooks := []PublicDomainBookRecord{} 93 | books.List(&badBooks, &airtable.Options{ 94 | Fields: []string{"Title", "Author", "Rating"}, 95 | Filter: `{Rating} < 3`, 96 | }) 97 | for _, badBook := range badBooks { 98 | fmt.Println("deleting", badBook) 99 | books.Delete(&badBook) 100 | } 101 | } 102 | ``` 103 | 104 | ## Contributing 105 | 106 | TBD 107 | -------------------------------------------------------------------------------- /options.go: -------------------------------------------------------------------------------- 1 | package airtable 2 | 3 | import ( 4 | "fmt" 5 | "net/url" 6 | "reflect" 7 | "strings" 8 | ) 9 | 10 | // SortType indicates which direction to sort the results in. 11 | type SortType string 12 | 13 | // SortDesc and SortAsc are used in the Sort type to indicate the 14 | // direction of the sort. 15 | const ( 16 | SortDesc = "desc" 17 | SortAsc = "asc" 18 | ) 19 | 20 | // Options is used in the Table.List method to adjust and control the response 21 | type Options struct { 22 | // Sort the response. See the package example for usage usage 23 | Sort Sort 24 | 25 | // Which fields to include. Useful when you want to exclude certain 26 | // fields if you aren't using them to save on network cost. 27 | Fields []string 28 | 29 | // Maximum amount of record to return. If MaxRecords <= 100, it is 30 | // guaranteed the results will fit in one network request. 31 | MaxRecords uint 32 | 33 | // Formula used to filer the results. See the airtable formula 34 | // reference for more details on how to create a formula: 35 | // https://support.airtable.com/hc/en-us/articles/203255215-Formula-Field-Reference 36 | Filter string 37 | 38 | // Name of the view to use. If set, only the records in that view 39 | // will be returned. The records will be sorted and filtered 40 | // according to the order of the view. 41 | View string 42 | 43 | // Airtable API performs automatic data conversion from string 44 | // values if typecast parameter is passed in. Automatic conversion 45 | // is disabled by default to ensure data integrity, but it may be 46 | // helpful for integrating with 3rd party data sources. 47 | Typecast bool 48 | 49 | offset string 50 | typ reflect.Type 51 | } 52 | 53 | // Sort represents a pair of strings: a field and a SortType 54 | type Sort [][2]string 55 | 56 | func (o *Options) setType(t reflect.Type) { 57 | o.typ = t 58 | } 59 | 60 | // Encode turns the Options object into a query string for use in URLs. 61 | func (o Options) Encode() string { 62 | q := []string{} 63 | 64 | if o.offset != "" { 65 | q = append(q, "offset="+esc(o.offset)) 66 | } 67 | 68 | if o.Typecast != false { 69 | q = append(q, "typecast=true") 70 | } 71 | 72 | if o.Filter != "" { 73 | q = append(q, "filterByFormula="+esc(o.Filter)) 74 | } 75 | 76 | if o.View != "" { 77 | q = append(q, "view="+esc(o.View)) 78 | } 79 | 80 | if o.MaxRecords != 0 { 81 | q = append(q, fmt.Sprintf("maxRecords=%d", o.MaxRecords)) 82 | } 83 | 84 | // This creates encoded version of something like this: 85 | // "sort[0][field]=Name&sort[0][direction]=desc". It will look up 86 | // the JSON tag on the related field in the struct passed in to 87 | // hold the response. If there's no JSON tag, it uses the raw 88 | // field name. 89 | if len(o.Sort) != 0 { 90 | for i, sort := range o.Sort { 91 | field, direction := getFieldJSONName(sort[0], o.typ), sort[1] 92 | sortstr := fmt.Sprintf("%s=%s&%s=%s", 93 | esc(fmt.Sprintf("sort[%d][field]", i)), 94 | esc(field), 95 | esc(fmt.Sprintf("sort[%d][direction]", i)), 96 | esc(direction), 97 | ) 98 | q = append(q, sortstr) 99 | } 100 | } 101 | 102 | if len(o.Fields) != 0 { 103 | for i, name := range o.Fields { 104 | field := getFieldJSONName(name, o.typ) 105 | fieldstr := fmt.Sprintf("%s=%s", 106 | esc(fmt.Sprintf("fields[%d]", i)), 107 | esc(field), 108 | ) 109 | q = append(q, fieldstr) 110 | } 111 | } 112 | 113 | query := strings.Join(q, "&") 114 | return query 115 | } 116 | 117 | func getFieldJSONName(field string, t reflect.Type) string { 118 | fields, _ := t.FieldByName("Fields") 119 | f, ok := fields.Type.FieldByName(field) 120 | if !ok { 121 | panic(fmt.Errorf("could not sort by %s: no such field in %s", field, t)) 122 | } 123 | if json, ok := f.Tag.Lookup("json"); ok { 124 | field = json 125 | } 126 | return field 127 | } 128 | 129 | func esc(s string) string { 130 | return url.QueryEscape(s) 131 | } 132 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. 374 | -------------------------------------------------------------------------------- /airtable.go: -------------------------------------------------------------------------------- 1 | // Package airtable provides a high-level client to the Airtable API 2 | // that allows the consumer to drop to a low-level request client when 3 | // needed. 4 | package airtable 5 | 6 | import ( 7 | "encoding/json" 8 | "fmt" 9 | "io" 10 | "io/ioutil" 11 | "net/http" 12 | "net/url" 13 | "path" 14 | "reflect" 15 | "strings" 16 | "time" 17 | 18 | "go.uber.org/ratelimit" 19 | ) 20 | 21 | var ( 22 | DefaultRootURL = "https://api.airtable.com" 23 | DefaultVersion = "v0" 24 | DefaultHTTPClient = http.DefaultClient 25 | DefaultLimiter = RateLimiter(5) // per second 26 | ) 27 | 28 | // RateLimiter makes a new rate limiter using n as the number of 29 | // requests per second that is allowed. If 0 is passed, the limiter will 30 | // be unlimited. 31 | func RateLimiter(n int) ratelimit.Limiter { 32 | if n == 0 { 33 | return ratelimit.NewUnlimited() 34 | } 35 | return ratelimit.New(n) 36 | } 37 | 38 | // QueryEncoder encodes options to a query string. 39 | type QueryEncoder interface { 40 | Encode() string 41 | } 42 | 43 | // Client represents an interface to communicate with the Airtable API. 44 | // 45 | // - APIKey: api key to use for each request. Requests will panic 46 | // if this is not set. 47 | // 48 | // - BaseID: base this client will operate against. Requests will panic 49 | // if this not set. 50 | // 51 | // - Version: version of the API to use. 52 | // 53 | // - RootURL: root URL to use. 54 | // 55 | // - HTTPClient: http.Client instance to use. 56 | // http.DefaultClient 57 | // 58 | // - Limit: max requests to make per second. 59 | type Client struct { 60 | APIKey string 61 | BaseID string 62 | Version string 63 | RootURL string 64 | HTTPClient *http.Client 65 | Limiter ratelimit.Limiter 66 | } 67 | 68 | // Request makes an HTTP request to the Airtable API without a body. See 69 | // RequestWithBody for documentation. 70 | func (c *Client) Request( 71 | method string, 72 | endpoint string, 73 | options QueryEncoder, 74 | ) ([]byte, error) { 75 | return c.RequestWithBody(method, endpoint, options, http.NoBody) 76 | } 77 | 78 | // ErrClientRequest is returned when the client runs into 79 | // problems making a request. 80 | type ErrClientRequest struct { 81 | Err error 82 | Method string 83 | URL string 84 | } 85 | 86 | func (e ErrClientRequest) Error() string { 87 | return fmt.Sprintf("airtable client request error: %s %s: %s", e.Method, e.URL, e.Err) 88 | } 89 | 90 | // RequestWithBody makes an HTTP request to the Airtable API. endpoint 91 | // will be combined with the client's RootlURL, Version and BaseID, to 92 | // create the complete URL. endpoint is expected to already be encoded; 93 | // if necessary, use url.PathEscape before passing RequestWithBody. 94 | // 95 | // If client is missing APIKey or BaseID, this method will panic. 96 | func (c *Client) RequestWithBody( 97 | method string, 98 | endpoint string, 99 | options QueryEncoder, 100 | body io.Reader, 101 | ) ([]byte, error) { 102 | var err error 103 | 104 | // finish setup or panic if the client isn't configured correctly 105 | c.checkSetup() 106 | 107 | if options == nil { 108 | options = url.Values{} 109 | } 110 | url := c.makeURL(endpoint, options) 111 | req, err := http.NewRequest(method, url, body) 112 | 113 | if err != nil { 114 | return nil, ErrClientRequest{ 115 | Err: err, 116 | URL: url, 117 | Method: method, 118 | } 119 | } 120 | 121 | c.makeHeader(req) 122 | 123 | // Take() will block until we can safely make the next request 124 | // without going over the rate limit 125 | c.Limiter.Take() 126 | 127 | resp, err := c.HTTPClient.Do(req) 128 | if err != nil { 129 | return nil, ErrClientRequest{ 130 | Err: err, 131 | URL: url, 132 | Method: method, 133 | } 134 | } 135 | 136 | bytes, err := ioutil.ReadAll(resp.Body) 137 | if err != nil { 138 | return nil, ErrClientRequest{ 139 | Err: err, 140 | URL: url, 141 | Method: method, 142 | } 143 | } 144 | 145 | if err = checkErrorResponse(bytes); err != nil { 146 | return bytes, ErrClientRequest{ 147 | Err: err, 148 | URL: url, 149 | Method: method, 150 | } 151 | } 152 | 153 | return bytes, nil 154 | } 155 | 156 | // Table returns a new Table that will use this client and operate 157 | // against the table with the passed in name 158 | func (c *Client) Table(name string) Table { 159 | return Table{ 160 | client: c, 161 | name: name, 162 | } 163 | } 164 | 165 | func (c *Client) makeHeader(r *http.Request) { 166 | r.Header = http.Header{} 167 | r.Header.Add("Authorization", fmt.Sprintf("Bearer %s", c.APIKey)) 168 | r.Header.Add("Content-Type", "application/json") 169 | } 170 | 171 | func (c *Client) checkSetup() { 172 | if c.BaseID == "" { 173 | panic("airtable: Client missing BaseID") 174 | } 175 | if c.APIKey == "" { 176 | panic("airtable: Client missing APIKey") 177 | } 178 | if c.HTTPClient == nil { 179 | c.HTTPClient = DefaultHTTPClient 180 | } 181 | if c.Version == "" { 182 | c.Version = DefaultVersion 183 | } 184 | if c.RootURL == "" { 185 | c.RootURL = DefaultRootURL 186 | } 187 | if c.Limiter == nil { 188 | c.Limiter = DefaultLimiter 189 | } 190 | } 191 | 192 | func (c *Client) makeURL(resource string, options QueryEncoder) string { 193 | q := options.Encode() 194 | p := resource 195 | uri := fmt.Sprintf("%s/%s/%s/%s?%s", 196 | c.RootURL, c.Version, c.BaseID, p, q) 197 | return uri 198 | } 199 | 200 | type genericErrorResponse struct { 201 | Error interface{} `json:"error"` 202 | } 203 | 204 | func checkErrorResponse(b []byte) error { 205 | var generic genericErrorResponse 206 | if err := json.Unmarshal(b, &generic); err != nil { 207 | return fmt.Errorf("couldn't unmarshal response: %s", err) 208 | } 209 | if generic.Error == nil { 210 | return nil 211 | } 212 | return fmt.Errorf("%s", generic.Error) 213 | } 214 | 215 | // Record is a convenience struct for anonymous inclusion in 216 | // user-constructed record structs. 217 | type Record struct { 218 | ID string 219 | CreatedTime time.Time 220 | } 221 | 222 | // Fields is used in NewRecord for constructing new records. 223 | type Fields map[string]interface{} 224 | 225 | // NewRecord is a convenience method for applying a map of fields to a 226 | // record container when the Fields struct is anonymous. 227 | func NewRecord(recordPtr interface{}, data Fields) { 228 | // panic if the recordPtr doesn't point to a record. 229 | validateRecordArg(recordPtr) 230 | 231 | // iterating over the container fields and applying those keys to 232 | // the passed in fields would be "safer", but it could possibly 233 | // mask user error if data is the complete wrong fit. instead we 234 | // can iterate over data and apply that to the container, and fail 235 | // early if there isn't a matching field. 236 | ref := reflect.ValueOf(recordPtr).Elem() 237 | typ := ref.Type() 238 | fields := ref.FieldByName("Fields") 239 | for k, v := range data { 240 | f := fields.FieldByName(k) 241 | val := reflect.ValueOf(v) 242 | if !f.IsValid() { 243 | errstr := fmt.Sprintf("airtable.NewRecord: cannot find field %s.%s", typ, k) 244 | panic(errstr) 245 | } 246 | if fkind, vkind := f.Kind(), val.Kind(); fkind != vkind { 247 | errstr := fmt.Sprintf("airtable.NewRecord: type error setting %s.%s: %s != %s", typ, k, fkind, vkind) 248 | panic(errstr) 249 | } 250 | f.Set(val) 251 | } 252 | } 253 | 254 | type deleteResponse struct { 255 | Deleted bool 256 | ID string 257 | } 258 | 259 | // Table represents an table in a base and provides methods for 260 | // interacting with records in the table. 261 | type Table struct { 262 | name string 263 | client *Client 264 | } 265 | 266 | // Get looks up a record from the table by ID and stores in in the 267 | // object pointed to by recordPtr. 268 | func (t *Table) Get(id string, recordPtr interface{}) error { 269 | bytes, err := t.client.Request("GET", t.makePath(id), nil) 270 | if err != nil { 271 | return err 272 | } 273 | return json.Unmarshal(bytes, recordPtr) 274 | } 275 | 276 | func validateRecordArg(recordPtr interface{}) { 277 | // must be: 278 | // ... a pointer 279 | typ := reflect.TypeOf(recordPtr) 280 | recordPtrKind := typ.Kind() 281 | if recordPtrKind != reflect.Ptr { 282 | panic(fmt.Errorf("airtable type error: recordPtr must be a pointer, got %s", recordPtrKind)) 283 | } 284 | 285 | // ... to a struct 286 | record := typ.Elem() 287 | recordKind := record.Kind() 288 | if recordKind != reflect.Struct { 289 | panic(fmt.Errorf("airtable type error: recordPtr must point to a struct, got %s", recordKind)) 290 | } 291 | 292 | // ... which has a field named "Fields" that's a struct 293 | fields, ok := record.FieldByName("Fields") 294 | if !ok { 295 | panic(fmt.Errorf("airtable type error: recordPtr must point to a struct with field 'Fields'")) 296 | } 297 | fieldsKind := fields.Type.Kind() 298 | if fieldsKind != reflect.Struct { 299 | panic(fmt.Errorf("airtable type error: recordPtr must point to a struct with field 'Fields' that is a struct, got %s", fieldsKind)) 300 | } 301 | 302 | // ... an optional field named "Typecast" that's a bool 303 | typecast, ok := record.FieldByName("Typecast") 304 | if ok { 305 | typecastKind := typecast.Type.Kind() 306 | if typecastKind != reflect.Bool { 307 | panic(fmt.Errorf("airtable type error: recordPtr must point to a struct with field 'Typecast' that is a bool, got %s", typecastKind)) 308 | } 309 | } 310 | 311 | // ... and a field named "ID" that's a string 312 | id, ok := record.FieldByName("ID") 313 | if !ok { 314 | panic(fmt.Errorf("airtable type error: recordPtr must point to a struct with field 'ID'")) 315 | } 316 | idKind := id.Type.Kind() 317 | if idKind != reflect.String { 318 | panic(fmt.Errorf("airtable type error: recordPtr must point to a struct with field 'ID' that is a string, got %s", idKind)) 319 | } 320 | } 321 | 322 | // Update sends the updated record pointed to by recordPtr to the table 323 | func (t *Table) Update(recordPtr interface{}) error { 324 | // panic if the recordPtr doesn't point to a record. 325 | validateRecordArg(recordPtr) 326 | 327 | id := getID(recordPtr) 328 | 329 | // panic makeJSONBody errors because it's an upstream programming 330 | // error that needs to be fixed, not a user input error or a network 331 | // condition. 332 | body, err := makeJSONBody(recordPtr) 333 | if err != nil { 334 | panic(fmt.Errorf("airtable.Table#Update: unable to create JSON (%s)", err)) 335 | } 336 | _, err = t.client.RequestWithBody("PATCH", t.makePath(id), Options{}, body) 337 | if err != nil { 338 | return err 339 | } 340 | return nil 341 | } 342 | 343 | // Create makes a new record in the table using the record pointed to by 344 | // recordPtr. On success, updates the ID and CreatedTime of the object 345 | // pointed to by recordPtr. 346 | // 347 | // recordPtr MUST have a Fields field that is a struct that can be 348 | // marshaled to JSON or this method will panic. 349 | func (t *Table) Create(recordPtr interface{}) error { 350 | // panic if the recordPtr doesn't point to a record. 351 | validateRecordArg(recordPtr) 352 | 353 | body, err := makeJSONBody(recordPtr) 354 | 355 | // panic if we can't create the JSON because it's an upstream 356 | // programming error that needs to be fixed, not a user input error 357 | // or a network condition. 358 | if err != nil { 359 | panic(fmt.Errorf("airtable.Table#Create: unable to create JSON (%s)", err)) 360 | } 361 | 362 | res, err := t.client.RequestWithBody("POST", t.makePath(""), Options{}, body) 363 | if err != nil { 364 | return err 365 | } 366 | return json.Unmarshal(res, recordPtr) 367 | } 368 | 369 | // Delete removes a record from the table. On success, ID and 370 | // CreatedTime of the object pointed to by recordPtr are removed. 371 | func (t *Table) Delete(recordPtr interface{}) error { 372 | // panic if the recordPtr doesn't point to a record. 373 | validateRecordArg(recordPtr) 374 | 375 | id := getID(recordPtr) 376 | 377 | res, err := t.client.Request("DELETE", t.makePath(id), Options{}) 378 | if err != nil { 379 | return fmt.Errorf("airtable.Table#Delete: request error %s", err) 380 | } 381 | deleted := deleteResponse{} 382 | if err := json.Unmarshal(res, &deleted); err != nil { 383 | return fmt.Errorf("airtable.Table#Delete: could not unpack request %s", err) 384 | } 385 | if !deleted.Deleted { 386 | return fmt.Errorf("airtable.Table#Delete: did not delete, %s", res) 387 | } 388 | markAsDeleted(recordPtr) 389 | return nil 390 | } 391 | 392 | // makeResponseContainer returns a new struct based on listPtr that can 393 | // contain the response from a list query to an airtable. For example: 394 | // 395 | // type BookRecord struct { 396 | // airtable.Record 397 | // Fields struct { 398 | // Title string 399 | // Author string 400 | // } 401 | // } 402 | // listPtr := &[]BookRecord{} 403 | // 404 | // Passing the above listPtr to makeResponseContainer will dynamically 405 | // create a struct that looks like this: 406 | // 407 | // struct { 408 | // Records []BookRecord 409 | // Offset string 410 | // } 411 | func makeResponseContainer(listPtr interface{}) reflect.Value { 412 | responseType := reflect.StructOf([]reflect.StructField{ 413 | {Name: "Records", Type: reflect.TypeOf(listPtr).Elem()}, 414 | {Name: "Offset", Type: reflect.TypeOf("string")}, 415 | }) 416 | return reflect.New(responseType) 417 | } 418 | 419 | func getOffset(listResponseContainer reflect.Value) string { 420 | return listResponseContainer.Elem().FieldByName("Offset").String() 421 | } 422 | 423 | func appendRecordsToList(listPtr interface{}, results reflect.Value) { 424 | var ( 425 | original = reflect.ValueOf(listPtr).Elem() 426 | records = results.Elem().FieldByName("Records") 427 | updated = reflect.AppendSlice(original, records) 428 | ) 429 | original.Set(updated) 430 | } 431 | 432 | // getRecordType will get the base element type from a pointer to a 433 | // slice. For example: getRecordType(*[]string) -> string 434 | func getRecordType(ps interface{}) reflect.Type { 435 | return reflect.TypeOf(ps).Elem().Elem() 436 | } 437 | 438 | func validateListArg(listPtr interface{}) { 439 | // must be: 440 | // ... a pointer 441 | typ := reflect.TypeOf(listPtr) 442 | listPtrKind := typ.Kind() 443 | if listPtrKind != reflect.Ptr { 444 | panic(fmt.Errorf("airtable type error: listPtr must be a pointer, got %s", listPtrKind)) 445 | } 446 | 447 | // ... to a slice 448 | list := typ.Elem() 449 | listKind := list.Kind() 450 | if listKind != reflect.Slice { 451 | panic(fmt.Errorf("airtable type error: listPtr must point to a slice, got %s", listKind)) 452 | } 453 | 454 | // ... whose elements are structs 455 | elem := list.Elem() 456 | elemKind := elem.Kind() 457 | if elemKind != reflect.Struct { 458 | panic(fmt.Errorf("airtable type error: listPtr must point to a slice of structs, got %s", elemKind)) 459 | } 460 | 461 | // ... the structs have a field named "Fields" that's a struct 462 | fields, ok := elem.FieldByName("Fields") 463 | if !ok { 464 | panic(fmt.Errorf("airtable type error: listPtr must point to a slice of structs with field 'Fields'")) 465 | } 466 | 467 | fieldsKind := fields.Type.Kind() 468 | if fieldsKind != reflect.Struct { 469 | panic(fmt.Errorf("airtable type error: listPtr must point to a slice of structs with field 'Fields' that is a struct, got %s", fieldsKind)) 470 | } 471 | 472 | // ... and a field named "ID" that's a string 473 | id, ok := elem.FieldByName("ID") 474 | if !ok { 475 | panic(fmt.Errorf("airtable type error: listPtr must point to a slice of structs with field 'ID'")) 476 | } 477 | 478 | idKind := id.Type.Kind() 479 | if idKind != reflect.String { 480 | panic(fmt.Errorf("airtable type error: listPtr must point to a slice of structs with field 'ID' that is a string, got %s", idKind)) 481 | } 482 | } 483 | 484 | // List queries the table for list of records and stores it in the 485 | // object pointed to by listPtr. By default, List will recurse to get 486 | // all of the records until there are no more left to get, but this can 487 | // be overriden by using the MaxRecords option. See Options for a 488 | // complete list of the options that are supported. 489 | // 490 | // listPtr must be a pointer to a slice of records, which are structs 491 | // that contain, at a minimum, `ID string` and `Fields struct {...}` 492 | // fields. For example: 493 | // 494 | // type BookRecord struct { 495 | // airtable.Record // provides ID and CreatedTime 496 | // Fields struct { 497 | // Title string 498 | // Author string 499 | // } 500 | // } 501 | // listPtr := &[]BookRecord{} 502 | // 503 | // This will be validated and cause a panic at runtime if listPtr is the 504 | // wrong type. 505 | func (t *Table) List(listPtr interface{}, options *Options) error { 506 | validateListArg(listPtr) 507 | 508 | if options == nil { 509 | options = &Options{} 510 | } 511 | 512 | // for "sort" and "fields" we need to have access to the type of 513 | // record so we can look up the JSON names of the fields. 514 | options.setType(getRecordType(listPtr)) 515 | 516 | for { 517 | container := makeResponseContainer(listPtr) 518 | bytes, err := t.client.Request("GET", t.makePath(""), options) 519 | if err != nil { 520 | return err 521 | } 522 | err = json.Unmarshal(bytes, container.Interface()) 523 | if err != nil { 524 | return err 525 | } 526 | appendRecordsToList(listPtr, container) 527 | options.offset = getOffset(container) 528 | if options.offset == "" { 529 | break 530 | } 531 | } 532 | return nil 533 | } 534 | 535 | func (t *Table) makePath(id string) string { 536 | name := url.PathEscape(t.name) 537 | if id == "" { 538 | return name 539 | } 540 | return path.Join(name, id) 541 | } 542 | 543 | func markAsDeleted(recordPtr interface{}) { 544 | var ( 545 | record = reflect.ValueOf(recordPtr).Elem() 546 | zeroTime = reflect.ValueOf(time.Time{}) 547 | id = record.FieldByName("ID") 548 | created = record.FieldByName("CreatedTime") 549 | ) 550 | if id.IsValid() { 551 | id.SetString("") 552 | } 553 | if created.IsValid() { 554 | created.Set(zeroTime) 555 | } 556 | } 557 | 558 | // makeJSONBody returns an io.Reader prepared for use in either Create 559 | // or Update operations. 560 | func makeJSONBody(recordPtr interface{}) (io.Reader, error) { 561 | f := getFields(recordPtr) 562 | b, err := json.Marshal(f) 563 | if err != nil { 564 | return nil, err 565 | } 566 | t := getTypecast(recordPtr) 567 | jsonstr := fmt.Sprintf(`{"fields": %s, "typecast": %t}`, b, t) 568 | body := strings.NewReader(jsonstr) 569 | return body, nil 570 | } 571 | 572 | func getFields(ptr interface{}) interface{} { 573 | return reflect.ValueOf(ptr).Elem().FieldByName("Fields").Interface() 574 | } 575 | 576 | func getTypecast(ptr interface{}) interface{} { 577 | if reflect.ValueOf(ptr).Elem().FieldByName("Typecast").IsValid() { 578 | return reflect.ValueOf(ptr).Elem().FieldByName("Typecast").Interface() 579 | } 580 | return false 581 | } 582 | 583 | func getID(ptr interface{}) string { 584 | return reflect.ValueOf(ptr).Elem().FieldByName("ID").String() 585 | } 586 | --------------------------------------------------------------------------------