-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquery_params.go
More file actions
58 lines (49 loc) · 1.63 KB
/
Copy pathquery_params.go
File metadata and controls
58 lines (49 loc) · 1.63 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
package didww
import (
"fmt"
"net/url"
"strings"
)
// QueryParams builds query parameters for DIDWW API requests.
type QueryParams struct {
values url.Values
}
// NewQueryParams creates a new QueryParams builder.
func NewQueryParams() *QueryParams {
return &QueryParams{values: url.Values{}}
}
// Filter adds a filter parameter: filter[key]=value.
func (q *QueryParams) Filter(key, value string) *QueryParams {
q.values.Set(fmt.Sprintf("filter[%s]", key), value)
return q
}
// Sort sets the sort parameter with comma-separated fields.
// Prefix with "-" for descending order.
func (q *QueryParams) Sort(fields ...string) *QueryParams {
q.values.Set("sort", strings.Join(fields, ","))
return q
}
// Include sets the include parameter for related resources.
func (q *QueryParams) Include(relations ...string) *QueryParams {
q.values.Set("include", strings.Join(relations, ","))
return q
}
// Page sets pagination parameters.
func (q *QueryParams) Page(number, size int) *QueryParams {
q.values.Set("page[number]", fmt.Sprintf("%d", number))
q.values.Set("page[size]", fmt.Sprintf("%d", size))
return q
}
// Fields sets sparse fieldsets for a resource type.
func (q *QueryParams) Fields(resourceType string, fields ...string) *QueryParams {
q.values.Set(fmt.Sprintf("fields[%s]", resourceType), strings.Join(fields, ","))
return q
}
// Encode returns the URL-encoded query string.
// Brackets are kept unescaped for JSON:API compatibility (filter[key]=value).
func (q *QueryParams) Encode() string {
encoded := q.values.Encode()
encoded = strings.ReplaceAll(encoded, "%5B", "[")
encoded = strings.ReplaceAll(encoded, "%5D", "]")
return encoded
}