generated from oklookat/gostarter
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.go
186 lines (164 loc) · 4.52 KB
/
util.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
package govkm
import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
"strconv"
"github.com/oklookat/govkm/schema"
"github.com/oklookat/vantuz"
)
// genApiPath создает URL-адрес для запроса к API, используя заданный путь.
//
// Пример использования: genApiPath([]string{"users", iToString(1234), "playlists", "list"})
//
// Результат: https://api.music.yandex.net/users/1234/playlists/list
func genApiPath(paths ...string) string {
if len(paths) == 0 {
return schema.ApiUrl
}
base := schema.ApiUrl + "/" + paths[0]
for i := 1; i < len(paths); i++ {
if len(paths[i]) == 0 {
continue
}
base += "/" + paths[i]
}
return base
}
var (
// Странная ошибка.
ErrNilResponse = errors.New(_errPrefix + ": nil http response")
)
func checkResponse[T any](resp *vantuz.Response, respError *schema.ResponseError, data *schema.Response[T]) error {
if resp == nil {
return ErrNilResponse
}
if resp.IsSuccess() {
return nil
}
if respError != nil && len(respError.Error()) > 0 {
return fmt.Errorf("%s: %w", _errPrefix, respError)
}
return fmt.Errorf("%s: %w", _errPrefix, schema.NewErrorWithStatusCode(resp.StatusCode))
}
func getLiked[T any](ctx context.Context, client *Client, entityName string, limit, offset int) (*schema.Response[T], error) {
// "liked/" - со слешем в конце. Так и задумано.
endpoint := genApiPath("user", entityName, "liked/")
params := getLimitOffset(limit, offset)
data := &schema.Response[T]{}
respErr := &schema.ResponseError{}
resp, err := client.Http.R().
SetQueryParams(params).
SetError(respErr).
SetResult(&data).
Get(ctx, endpoint)
if err == nil {
err = checkResponse(resp, respErr, data)
}
return data, err
}
func getEntityById[T any](ctx context.Context, client *Client, entityName string, id schema.ID) (*schema.Response[T], error) {
endpoint := genApiPath(entityName, id.String())
data := &schema.Response[T]{}
respErr := &schema.ResponseError{}
resp, err := client.Http.R().
SetError(respErr).
SetResult(&data).
Get(ctx, endpoint)
if err == nil {
err = checkResponse(resp, respErr, data)
}
return data, err
}
func getAny[T any](ctx context.Context, client *Client, queryParams url.Values, paths ...string) (*schema.Response[T], error) {
endpoint := genApiPath(paths...)
data := &schema.Response[T]{}
respErr := &schema.ResponseError{}
req := client.Http.R().
SetError(respErr).
SetResult(&data)
if queryParams != nil {
req.SetQueryParams(queryParams)
}
resp, err := req.Get(ctx, endpoint)
if err == nil {
err = checkResponse(resp, respErr, data)
}
return data, err
}
func writeableAny[T any](ctx context.Context, client *Client, method string, body url.Values, paths ...string) (*schema.Response[T], error) {
endpoint := genApiPath(paths...)
data := &schema.Response[T]{}
respErr := &schema.ResponseError{}
req := client.Http.R().
SetError(respErr).
SetResult(&data)
if body != nil {
req.SetFormUrlValues(body)
}
var (
resp *vantuz.Response
err error
)
switch method {
case http.MethodPost:
resp, err = req.Post(ctx, endpoint)
case http.MethodPut:
resp, err = req.Put(ctx, endpoint)
case http.MethodDelete:
resp, err = req.Delete(ctx, endpoint)
}
if err == nil {
err = checkResponse(resp, respErr, data)
}
return data, err
}
func getLimitOffset(limit, offset int) url.Values {
params := url.Values{}
if offset > 0 {
params.Set("offset", strconv.Itoa(offset))
}
if limit == 0 {
limit = 1
}
params.Set("limit", strconv.Itoa(limit))
return params
}
func searchEntity[T any](ctx context.Context, client *Client,
query, entityType string, limit, offset int) (*schema.Response[T], error) {
params := getLimitOffset(limit, offset)
params.Set("q", query)
return getAny[T](ctx, client, params, "search", entityType, "/")
}
func likeUnlikeEntity(
ctx context.Context,
client *Client,
entityType string,
entityId schema.ID,
like bool,
) (*schema.Response[any], error) {
endpoint := genApiPath(entityType, entityId.String(), "like")
data := &schema.Response[any]{}
respErr := &schema.ResponseError{}
req := client.Http.R().SetError(respErr).SetResult(&data)
var resp *vantuz.Response
var err error
if like {
resp, err = req.Put(ctx, endpoint)
} else {
resp, err = req.Delete(ctx, endpoint)
}
if err == nil {
err = checkResponse(resp, respErr, data)
}
return data, err
}
func valuesFileId(id []schema.ID) url.Values {
params := url.Values{}
for _, id := range id {
params.Add("file_id", id.String())
}
return params
}