-
Notifications
You must be signed in to change notification settings - Fork 19
/
request_builder.go
376 lines (320 loc) · 11.4 KB
/
request_builder.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
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
package postgrest_go
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
)
// RequestError represents an error response from the PostgREST server.
type RequestError struct {
Message string `json:"message"`
Details string `json:"details"`
Hint string `json:"hint"`
Code string `json:"code"`
HTTPStatusCode int `json:"-"`
}
func (rq *RequestError) Error() string {
return fmt.Sprintf("%s: %s", rq.Code, rq.Message)
}
// RequestBuilder represents a builder for PostgREST requests.
type RequestBuilder struct {
client *Client
path string
params url.Values
header http.Header
}
// Select starts building a SELECT request with the specified columns.
func (b *RequestBuilder) Select(columns ...string) *SelectRequestBuilder {
b.params.Set("select", strings.Join(columns, ","))
return &SelectRequestBuilder{
FilterRequestBuilder{
QueryRequestBuilder: QueryRequestBuilder{
client: b.client,
path: b.path,
httpMethod: "GET",
header: b.header,
params: b.params,
},
negateNext: false,
},
}
}
// Insert starts building an INSERT request with the provided JSON data.
func (b *RequestBuilder) Insert(json interface{}) *QueryRequestBuilder {
b.header.Set("Prefer", "return=representation")
return &QueryRequestBuilder{
client: b.client,
path: b.path,
httpMethod: http.MethodPost,
json: json,
params: b.params,
header: b.header,
}
}
// Upsert starts building an UPSERT request with the provided JSON data.
func (b *RequestBuilder) Upsert(json interface{}) *QueryRequestBuilder {
b.header.Set("Prefer", "return=representation,resolution=merge-duplicates")
return &QueryRequestBuilder{
client: b.client,
path: b.path,
httpMethod: http.MethodPost,
json: json,
params: b.params,
header: b.header,
}
}
// Update starts building an UPDATE request with the provided JSON data.
func (b *RequestBuilder) Update(json interface{}) *FilterRequestBuilder {
b.header.Set("Prefer", "return=representation")
return &FilterRequestBuilder{
QueryRequestBuilder: QueryRequestBuilder{
client: b.client,
path: b.path,
httpMethod: http.MethodPatch,
json: json,
params: b.params,
header: b.header,
},
negateNext: false,
}
}
// Delete starts building a DELETE request.
func (b *RequestBuilder) Delete() *FilterRequestBuilder {
return &FilterRequestBuilder{
QueryRequestBuilder: QueryRequestBuilder{
client: b.client,
path: b.path,
httpMethod: http.MethodDelete,
json: nil,
params: b.params,
header: b.header,
},
negateNext: false,
}
}
// QueryRequestBuilder represents a builder for query requests.
type QueryRequestBuilder struct {
client *Client
params url.Values
header http.Header
path string
httpMethod string
json interface{}
}
// Execute sends the query request and unmarshals the response JSON into the provided object.
func (b *QueryRequestBuilder) Execute(r interface{}) error {
return b.ExecuteWithContext(context.Background(), r)
}
// ExecuteWithContext sends the query request with the provided context and unmarshals the response JSON into the provided object.
func (b *QueryRequestBuilder) ExecuteWithContext(ctx context.Context, r interface{}) error {
data, err := json.Marshal(b.json)
if err != nil {
return err
}
req, err := http.NewRequestWithContext(ctx, b.httpMethod, b.path, bytes.NewBuffer(data))
if err != nil {
return err
}
query, err := url.QueryUnescape(b.params.Encode())
if err != nil {
return err
}
req.URL.RawQuery = query
req.Header = b.client.Headers()
// Inject/override custom headers
for key, vals := range b.header {
for _, val := range vals {
req.Header.Set(key, val)
}
}
req.URL.Path = req.URL.Path[1:]
req.URL = b.client.Transport.baseURL.ResolveReference(req.URL)
resp, err := b.client.session.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
statusOK := resp.StatusCode >= 200 && resp.StatusCode < 300
if !statusOK {
reqError := RequestError{HTTPStatusCode: resp.StatusCode}
if err = json.Unmarshal(body, &reqError); err != nil {
return err
}
return &reqError
}
if resp.StatusCode != http.StatusNoContent && r != nil {
if err = json.Unmarshal(body, r); err != nil {
return err
}
}
return nil
}
// FilterRequestBuilder represents a builder for filter requests.
type FilterRequestBuilder struct {
QueryRequestBuilder
negateNext bool
}
// Not negates the next filter condition.
func (b *FilterRequestBuilder) Not() *FilterRequestBuilder {
b.negateNext = true
return b
}
// Filter adds a filter condition to the request.
func (b *FilterRequestBuilder) Filter(column, operator, criteria string) *FilterRequestBuilder {
if b.negateNext {
b.negateNext = false
operator = "not." + operator
}
b.params.Add(SanitizeParam(column), operator+"."+criteria)
return b
}
// Eq adds an equality filter condition to the request.
func (b *FilterRequestBuilder) Eq(column, value string) *FilterRequestBuilder {
return b.Filter(column, "eq", SanitizeParam(value))
}
// Neq adds a not-equal filter condition to the request.
func (b *FilterRequestBuilder) Neq(column, value string) *FilterRequestBuilder {
return b.Filter(column, "neq", SanitizeParam(value))
}
// Gt adds a greater-than filter condition to the request.
func (b *FilterRequestBuilder) Gt(column, value string) *FilterRequestBuilder {
return b.Filter(column, "gt", SanitizeParam(value))
}
// Gte adds a greater-than-or-equal filter condition to the request.
func (b *FilterRequestBuilder) Gte(column, value string) *FilterRequestBuilder {
return b.Filter(column, "gte", SanitizeParam(value))
}
// Lt adds a less-than filter condition to the request.
func (b *FilterRequestBuilder) Lt(column, value string) *FilterRequestBuilder {
return b.Filter(column, "lt", SanitizeParam(value))
}
// Lte adds a less-than-or-equal filter condition to the request.
func (b *FilterRequestBuilder) Lte(column, value string) *FilterRequestBuilder {
return b.Filter(column, "lte", SanitizeParam(value))
}
// Is adds an IS filter condition to the request.
func (b *FilterRequestBuilder) Is(column, value string) *FilterRequestBuilder {
return b.Filter(column, "is", SanitizeParam(value))
}
// Like adds a LIKE filter condition to the request.
func (b *FilterRequestBuilder) Like(column, value string) *FilterRequestBuilder {
return b.Filter(column, "like", SanitizeParam(value))
}
// Ilike adds a ILIKE filter condition to the request.
func (b *FilterRequestBuilder) Ilike(column, value string) *FilterRequestBuilder {
return b.Filter(column, "ilike", SanitizeParam(value))
}
// Fts adds a full-text search filter condition to the request.
func (b *FilterRequestBuilder) Fts(column, value string) *FilterRequestBuilder {
return b.Filter(column, "fts", SanitizeParam(value))
}
// Plfts adds a phrase-level full-text search filter condition to the request.
func (b *FilterRequestBuilder) Plfts(column, value string) *FilterRequestBuilder {
return b.Filter(column, "plfts", SanitizeParam(value))
}
// Phfts adds a phrase-headline-level full-text search filter condition to the request.
func (b *FilterRequestBuilder) Phfts(column, value string) *FilterRequestBuilder {
return b.Filter(column, "phfts", SanitizeParam(value))
}
// Wfts adds a word-level full-text search filter condition to the request.
func (b *FilterRequestBuilder) Wfts(column, value string) *FilterRequestBuilder {
return b.Filter(column, "wfts", SanitizeParam(value))
}
// In adds an IN filter condition to the request.
func (b *FilterRequestBuilder) In(column string, values []string) *FilterRequestBuilder {
sanitized := make([]string, len(values))
for i, value := range values {
sanitized[i] = SanitizeParam(value)
}
return b.Filter(column, "in", fmt.Sprintf("(%s)", strings.Join(sanitized, ",")))
}
// Cs adds a contains set filter condition to the request.
func (b *FilterRequestBuilder) Cs(column string, values []string) *FilterRequestBuilder {
sanitized := make([]string, len(values))
for i, value := range values {
sanitized[i] = SanitizeParam(value)
}
return b.Filter(column, "cs", fmt.Sprintf("{%s}", strings.Join(sanitized, ",")))
}
// Cd adds a contained by set filter condition to the request.
func (b *FilterRequestBuilder) Cd(column string, values []string) *FilterRequestBuilder {
sanitized := make([]string, len(values))
for i, value := range values {
sanitized[i] = SanitizeParam(value)
}
return b.Filter(column, "cd", fmt.Sprintf("{%s}", strings.Join(sanitized, ",")))
}
// Ov adds an overlaps set filter condition to the request.
func (b *FilterRequestBuilder) Ov(column string, values []string) *FilterRequestBuilder {
sanitized := make([]string, len(values))
for i, value := range values {
sanitized[i] = SanitizeParam(value)
}
return b.Filter(column, "ov", fmt.Sprintf("{%s}", strings.Join(sanitized, ",")))
}
// Sl adds a strictly left of filter condition to the request.
func (b *FilterRequestBuilder) Sl(column string, from, to int) *FilterRequestBuilder {
return b.Filter(column, "sl", fmt.Sprintf("(%d,%d)", from, to))
}
// Sr adds a strictly right of filter condition to the request.
func (b *FilterRequestBuilder) Sr(column string, from, to int) *FilterRequestBuilder {
return b.Filter(column, "sr", fmt.Sprintf("(%d,%d)", from, to))
}
// Nxl adds a not strictly left of filter condition to the request.
func (b *FilterRequestBuilder) Nxl(column string, from, to int) *FilterRequestBuilder {
return b.Filter(column, "nxl", fmt.Sprintf("(%d,%d)", from, to))
}
// Nxr adds a not strictly right of filter condition to the request.
func (b *FilterRequestBuilder) Nxr(column string, from, to int) *FilterRequestBuilder {
return b.Filter(column, "nxr", fmt.Sprintf("(%d,%d)", from, to))
}
// Ad adds an adjacent to filter condition to the request.
func (b *FilterRequestBuilder) Ad(column string, values []string) *FilterRequestBuilder {
sanitized := make([]string, len(values))
for i, value := range values {
sanitized[i] = SanitizeParam(value)
}
return b.Filter(column, "ad", fmt.Sprintf("{%s}", strings.Join(sanitized, ",")))
}
// FilterRequestBuilder represents a builder for SELECT requests.
type SelectRequestBuilder struct {
FilterRequestBuilder
}
// OrderBy sets the ordering column and direction for the SELECT request.
func (b *SelectRequestBuilder) OrderBy(column, direction string) *SelectRequestBuilder {
b.params.Set("order", column+"."+direction)
return b
}
// Range sets the range of rows to be returned for the SELECT request.
func (b *SelectRequestBuilder) Range(from, to int) *SelectRequestBuilder {
b.params.Set("range", fmt.Sprintf("%d-%d", from, to))
return b
}
// SingleRow sets the single row behavior for the SELECT request.
func (b *SelectRequestBuilder) SingleRow() *SelectRequestBuilder {
b.params.Set("single-row", "true")
return b
}
// OnlyPayload sets the only payload behavior for the SELECT request.
func (b *SelectRequestBuilder) OnlyPayload() *SelectRequestBuilder {
b.params.Set("only-payload", "true")
return b
}
// WithoutCount sets the without count behavior for the SELECT request.
func (b *SelectRequestBuilder) WithoutCount() *SelectRequestBuilder {
b.params.Set("without-count", "true")
return b
}
// SingleValue sets the single value behavior for the SELECT request.
func (b *SelectRequestBuilder) SingleValue() *SelectRequestBuilder {
b.params.Set("single-value", "true")
return b
}