-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
84 lines (67 loc) · 1.86 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
package turso
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
)
// Client manages communication with the Turso API
type Client struct {
cfg *Config
client HTTPRequestDoer
// Reuse a single struct instead of allocating one for each service on the heap
common service
// Services
Organization organizationService
Group groupService
Database databaseService
DatabaseTokens databaseTokensService
}
type service struct {
client *Client
}
// HTTPRequestDoer implements the standard http.Client interface
type HTTPRequestDoer interface {
Do(req *http.Request) (*http.Response, error)
}
// Client returns the http client
func (c *Client) Client() HTTPRequestDoer {
return c.client
}
// NewClient creates a new client for interacting with the Turso API
func NewClient(c Config) (*Client, error) {
if c.Token == "" {
return nil, ErrAPITokenNotSet
}
client := &Client{
cfg: &c,
}
if client.client == nil {
client.client = http.DefaultClient
}
client.common.client = client
// initialize services
client.Organization = (*OrganizationService)(&client.common)
client.Database = (*DatabaseService)(&client.common)
client.Group = (*GroupService)(&client.common)
client.DatabaseTokens = (*DatabaseTokensService)(&client.common)
return client, nil
}
// DoRequest performs an HTTP request and returns the response
func (c *Client) DoRequest(ctx context.Context, method string, url string, data interface{}) (*http.Response, error) {
var bodyReader io.Reader
buf, err := json.Marshal(data)
if err != nil {
return nil, err
}
bodyReader = bytes.NewReader(buf)
req, err := http.NewRequestWithContext(ctx, method, url, bodyReader)
if err != nil {
return nil, err
}
// Add Headers
req.Header.Add("Authorization", "Bearer "+c.cfg.Token)
req.Header.Add("Content-Type", "application/json")
return c.client.Do(req.WithContext(ctx))
}