-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathclient.go
More file actions
276 lines (237 loc) · 6.28 KB
/
Copy pathclient.go
File metadata and controls
276 lines (237 loc) · 6.28 KB
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
package postgrest
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"path"
"strings"
"sync"
)
var (
version = "v0.1.1"
)
// Client represents a PostgREST client
// Similar to PostgrestClient in postgrest-js
type Client struct {
ClientError error
session *http.Client
Transport *transport
schemaName string
}
// NewClientWithError constructs a new client given a URL to a Postgrest instance.
func NewClientWithError(rawURL, schema string, headers map[string]string) (*Client, error) {
// Create URL from rawURL
baseURL, err := url.Parse(rawURL)
if err != nil {
return nil, err
}
t := transport{
header: http.Header{},
baseURL: *baseURL,
Parent: nil,
}
c := Client{
session: &http.Client{Transport: &t},
Transport: &t,
schemaName: schema,
}
if schema == "" {
schema = "public"
c.schemaName = schema
}
// Set required headers
c.Transport.SetHeaders(map[string]string{
"Accept": "application/json",
"Content-Type": "application/json",
"Accept-Profile": schema,
"Content-Profile": schema,
"X-Client-Info": "postgrest-go/" + version,
})
// Set optional headers if they exist
c.Transport.SetHeaders(headers)
return &c, nil
}
// NewClient constructs a new client given a URL to a Postgrest instance.
func NewClient(rawURL, schema string, headers map[string]string) *Client {
client, err := NewClientWithError(rawURL, schema, headers)
if err != nil {
return &Client{ClientError: err}
}
return client
}
func (c *Client) PingWithError() error {
req, err := http.NewRequest("GET", path.Join(c.Transport.baseURL.Path, ""), nil)
if err != nil {
return err
}
resp, err := c.session.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return errors.New("ping failed")
}
return nil
}
func (c *Client) Ping() bool {
err := c.PingWithError()
if err != nil {
c.ClientError = err
return false
}
return true
}
// SetApiKey sets api key header for subsequent requests.
func (c *Client) SetApiKey(apiKey string) *Client {
c.Transport.SetHeader("apikey", apiKey)
return c
}
// SetAuthToken sets authorization header for subsequent requests.
func (c *Client) SetAuthToken(authToken string) *Client {
c.Transport.SetHeader("Authorization", "Bearer "+authToken)
return c
}
// ChangeSchema modifies the schema for subsequent requests.
func (c *Client) ChangeSchema(schema string) *Client {
c.schemaName = schema
c.Transport.SetHeaders(map[string]string{
"Accept-Profile": schema,
"Content-Profile": schema,
})
return c
}
// Schema selects a schema to query or perform an function (rpc) call
func (c *Client) Schema(schema string) *Client {
newClient := &Client{
session: c.session,
Transport: c.Transport,
schemaName: schema,
}
// Update schema headers
newClient.Transport.SetHeaders(map[string]string{
"Accept-Profile": schema,
"Content-Profile": schema,
})
return newClient
}
// From sets the table or view to query from
func (c *Client) From(relation string) *QueryBuilder[map[string]interface{}] {
return NewQueryBuilder[map[string]interface{}](c, relation)
}
// RpcOptions contains options for RPC
type RpcOptions struct {
Head bool
Get bool
Count string // "exact", "planned", or "estimated"
}
// Rpc performs a function call
func (c *Client) Rpc(fn string, args interface{}, opts *RpcOptions) *FilterBuilder[interface{}] {
if opts == nil {
opts = &RpcOptions{}
}
var method string
var body interface{}
rpcURL := c.Transport.baseURL.JoinPath("rpc", fn)
headers := make(http.Header)
if c.Transport != nil {
c.Transport.mu.RLock()
for key, values := range c.Transport.header {
for _, val := range values {
headers.Add(key, val)
}
}
c.Transport.mu.RUnlock()
}
if opts.Head || opts.Get {
if opts.Head {
method = "HEAD"
} else {
method = "GET"
}
// Add args as query parameters
if argsMap, ok := args.(map[string]interface{}); ok {
query := rpcURL.Query()
for name, value := range argsMap {
if value != nil {
// Handle array values
if arr, ok := value.([]interface{}); ok {
var strValues []string
for _, v := range arr {
strValues = append(strValues, fmt.Sprintf("%v", v))
}
query.Set(name, fmt.Sprintf("{%s}", strings.Join(strValues, ",")))
} else {
query.Set(name, fmt.Sprintf("%v", value))
}
}
}
rpcURL.RawQuery = query.Encode()
}
} else {
method = "POST"
body = args
}
if opts.Count != "" && (opts.Count == "exact" || opts.Count == "planned" || opts.Count == "estimated") {
headers.Add("Prefer", fmt.Sprintf("count=%s", opts.Count))
}
builder := NewBuilder[interface{}](c, method, rpcURL, &BuilderOptions{
Headers: headers,
Schema: c.schemaName,
Body: body,
})
return &FilterBuilder[interface{}]{Builder: builder}
}
// RpcWithError executes a Postgres function (a.k.a., Remote Procedure Call), given the
// function name and, optionally, a body, returning the result as a string.
func (c *Client) RpcWithError(name string, count string, rpcBody interface{}) (string, error) {
opts := &RpcOptions{Count: count}
filterBuilder := c.Rpc(name, rpcBody, opts)
response, err := filterBuilder.Execute(context.Background())
if err != nil {
return "", err
}
if response.Error != nil {
return "", response.Error
}
// Convert response.Data to string
dataBytes, _ := json.Marshal(response.Data)
return string(dataBytes), nil
}
type transport struct {
baseURL url.URL
Parent http.RoundTripper
mu sync.RWMutex
header http.Header
}
func (t *transport) SetHeader(key, value string) {
t.mu.Lock()
defer t.mu.Unlock()
t.header.Set(key, value)
}
func (t *transport) SetHeaders(headers map[string]string) {
t.mu.Lock()
defer t.mu.Unlock()
for key, value := range headers {
t.header.Set(key, value)
}
}
func (t *transport) RoundTrip(req *http.Request) (*http.Response, error) {
t.mu.RLock()
for headerName, values := range t.header {
for _, val := range values {
req.Header.Add(headerName, val)
}
}
t.mu.RUnlock()
req.URL = t.baseURL.ResolveReference(req.URL)
// This is only needed with usage of httpmock in testing. It would be better to initialize
// t.Parent with http.DefaultTransport and then use t.Parent.RoundTrip(req)
if t.Parent != nil {
return t.Parent.RoundTrip(req)
}
return http.DefaultTransport.RoundTrip(req)
}