2020-04-12 13:05:28 +03:00
|
|
|
package airtable
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"fmt"
|
|
|
|
|
"net/http"
|
2024-06-22 21:46:58 -07:00
|
|
|
"os"
|
2020-04-12 13:05:28 +03:00
|
|
|
"time"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
const (
|
2024-06-22 15:13:30 -07:00
|
|
|
defaultBaseURL = "https://api.airtable.com/v0"
|
|
|
|
|
defaultRateLimit = 4
|
2020-04-12 13:05:28 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
type Client struct {
|
2024-06-22 15:13:30 -07:00
|
|
|
Client *http.Client
|
|
|
|
|
BaseURL string
|
2024-06-22 15:33:14 -07:00
|
|
|
apiKey string
|
2020-04-12 13:05:28 +03:00
|
|
|
rateLimiter <-chan time.Time
|
|
|
|
|
}
|
|
|
|
|
|
2024-06-22 15:13:30 -07:00
|
|
|
func New(apiKey string) *Client {
|
|
|
|
|
c := &Client{
|
|
|
|
|
Client: http.DefaultClient,
|
|
|
|
|
BaseURL: defaultBaseURL,
|
2024-06-22 15:33:14 -07:00
|
|
|
apiKey: apiKey,
|
2020-04-12 13:05:28 +03:00
|
|
|
}
|
|
|
|
|
|
2024-06-22 15:13:30 -07:00
|
|
|
c.SetRateLimit(defaultRateLimit)
|
|
|
|
|
|
|
|
|
|
return c
|
2023-01-12 12:54:18 +05:00
|
|
|
}
|
|
|
|
|
|
2024-06-22 21:46:58 -07:00
|
|
|
func NewFromEnv() (*Client, error) {
|
|
|
|
|
apiKey := os.Getenv("AIRTABLE_TOKEN")
|
|
|
|
|
if apiKey == "" {
|
|
|
|
|
return nil, fmt.Errorf("please set $AIRTABLE_TOKEN")
|
2020-04-12 13:05:28 +03:00
|
|
|
}
|
2021-10-02 14:27:00 +03:00
|
|
|
|
2024-06-22 21:46:58 -07:00
|
|
|
return New(apiKey), nil
|
2024-06-22 15:13:30 -07:00
|
|
|
}
|
2021-10-02 14:27:00 +03:00
|
|
|
|
2024-06-22 21:46:58 -07:00
|
|
|
func (c *Client) SetRateLimit(rateLimit int) {
|
|
|
|
|
c.rateLimiter = time.Tick(time.Second / time.Duration(rateLimit))
|
2020-04-12 13:05:28 +03:00
|
|
|
}
|
|
|
|
|
|
2024-06-22 21:46:58 -07:00
|
|
|
func (c *Client) waitForRateLimit() {
|
|
|
|
|
<-c.rateLimiter
|
2024-06-22 15:33:14 -07:00
|
|
|
}
|