Files
airtable/client.go

54 lines
841 B
Go
Raw Normal View History

package airtable
import (
"fmt"
"net/http"
2024-06-22 21:46:58 -07:00
"os"
"time"
)
const (
2024-06-22 15:13:30 -07:00
defaultBaseURL = "https://api.airtable.com/v0"
defaultRateLimit = 4
)
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
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,
}
2024-06-22 15:13:30 -07:00
c.SetRateLimit(defaultRateLimit)
return c
}
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")
}
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))
}
2024-06-22 21:46:58 -07:00
func (c *Client) waitForRateLimit() {
<-c.rateLimiter
2024-06-22 15:33:14 -07:00
}
2024-06-23 16:32:28 -07:00
func P(s string) *string {
return &s
}