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
|
package linodego
import (
"context"
"encoding/json"
"fmt"
"net/url"
"reflect"
)
// paginatedResponse represents a single response from a paginated
// endpoint.
type paginatedResponse[T any] struct {
Page int `json:"page" url:"page,omitempty"`
Pages int `json:"pages" url:"pages,omitempty"`
Results int `json:"results" url:"results,omitempty"`
Data []T `json:"data"`
}
// handlePaginatedResults aggregates results from the given
// paginated endpoint using the provided ListOptions and HTTP method.
// nolint:funlen
func handlePaginatedResults[T any, O any](
ctx context.Context,
client *Client,
endpoint string,
opts *ListOptions,
method string,
options ...O,
) ([]T, error) {
result := make([]T, 0)
if opts == nil {
opts = &ListOptions{PageOptions: &PageOptions{Page: 0}}
}
if opts.PageOptions == nil {
opts.PageOptions = &PageOptions{Page: 0}
}
// Validate options
numOpts := len(options)
if numOpts > 1 {
return nil, fmt.Errorf("invalid number of options: expected 0 or 1, got %d", numOpts)
}
// Prepare request body if options are provided
var reqBody string
if numOpts > 0 && !isNil(options[0]) {
body, err := json.Marshal(options[0])
if err != nil {
return nil, fmt.Errorf("failed to marshal request body: %w", err)
}
reqBody = string(body)
}
// Makes a request to a particular page and appends the response to the result
handlePage := func(page int) error {
var resultType paginatedResponse[T]
// Override the page to be applied in applyListOptionsToRequest(...)
opts.Page = page
// This request object cannot be reused for each page request
// because it can lead to possible data corruption
req := client.R(ctx).SetResult(&resultType)
// Apply all user-provided list options to the request
if err := applyListOptionsToRequest(opts, req); err != nil {
return err
}
// Set request body if provided
if reqBody != "" {
req.SetBody(reqBody)
}
var response *paginatedResponse[T]
// Execute the appropriate HTTP method
switch method {
case "GET":
res, err := coupleAPIErrors(req.Get(endpoint))
if err != nil {
return err
}
response = res.Result().(*paginatedResponse[T])
case "PUT":
res, err := coupleAPIErrors(req.Put(endpoint))
if err != nil {
return err
}
response = res.Result().(*paginatedResponse[T])
default:
return fmt.Errorf("unsupported HTTP method: %s", method)
}
// Update pagination metadata
opts.Page = page
opts.Pages = response.Pages
opts.Results = response.Results
result = append(result, response.Data...)
return nil
}
// Determine starting page
startingPage := 1
pageDefined := opts.Page > 0
if pageDefined {
startingPage = opts.Page
}
// Get the first page
if err := handlePage(startingPage); err != nil {
return nil, err
}
// If the user has explicitly specified a page, we don't
// need to get any other pages.
if pageDefined {
return result, nil
}
// Get the rest of the pages
for page := 2; page <= opts.Pages; page++ {
if err := handlePage(page); err != nil {
return nil, err
}
}
return result, nil
}
// getPaginatedResults aggregates results from the given
// paginated endpoint using the provided ListOptions.
func getPaginatedResults[T any](
ctx context.Context,
client *Client,
endpoint string,
opts *ListOptions,
) ([]T, error) {
return handlePaginatedResults[T, any](ctx, client, endpoint, opts, "GET")
}
// putPaginatedResults sends a PUT request and aggregates the results from the given
// paginated endpoint using the provided ListOptions.
func putPaginatedResults[T, O any](
ctx context.Context,
client *Client,
endpoint string,
opts *ListOptions,
options ...O,
) ([]T, error) {
return handlePaginatedResults[T, O](ctx, client, endpoint, opts, "PUT", options...)
}
// doGETRequest runs a GET request using the given client and API endpoint,
// and returns the result
func doGETRequest[T any](
ctx context.Context,
client *Client,
endpoint string,
) (*T, error) {
var resultType T
req := client.R(ctx).SetResult(&resultType)
r, err := coupleAPIErrors(req.Get(endpoint))
if err != nil {
return nil, err
}
return r.Result().(*T), nil
}
// doPOSTRequest runs a PUT request using the given client, API endpoint,
// and options/body.
func doPOSTRequest[T, O any](
ctx context.Context,
client *Client,
endpoint string,
options ...O,
) (*T, error) {
var resultType T
numOpts := len(options)
if numOpts > 1 {
return nil, fmt.Errorf("invalid number of options: %d", len(options))
}
req := client.R(ctx).SetResult(&resultType)
if numOpts > 0 && !isNil(options[0]) {
body, err := json.Marshal(options[0])
if err != nil {
return nil, err
}
req.SetBody(string(body))
}
r, err := coupleAPIErrors(req.Post(endpoint))
if err != nil {
return nil, err
}
return r.Result().(*T), nil
}
// doPOSTRequestNoResponseBody runs a POST request using the given client, API endpoint,
// and options/body. It expects only empty response from the endpoint.
func doPOSTRequestNoResponseBody[T any](
ctx context.Context,
client *Client,
endpoint string,
options ...T,
) error {
_, err := doPOSTRequest[any, T](ctx, client, endpoint, options...)
return err
}
// doPOSTRequestNoRequestResponseBody runs a POST request where no request body is needed and no response body
// is expected from the endpoints.
func doPOSTRequestNoRequestResponseBody(
ctx context.Context,
client *Client,
endpoint string,
) error {
return doPOSTRequestNoResponseBody(ctx, client, endpoint, struct{}{})
}
// doPUTRequest runs a PUT request using the given client, API endpoint,
// and options/body.
func doPUTRequest[T, O any](
ctx context.Context,
client *Client,
endpoint string,
options ...O,
) (*T, error) {
var resultType T
numOpts := len(options)
if numOpts > 1 {
return nil, fmt.Errorf("invalid number of options: %d", len(options))
}
req := client.R(ctx).SetResult(&resultType)
if numOpts > 0 && !isNil(options[0]) {
body, err := json.Marshal(options[0])
if err != nil {
return nil, err
}
req.SetBody(string(body))
}
r, err := coupleAPIErrors(req.Put(endpoint))
if err != nil {
return nil, err
}
return r.Result().(*T), nil
}
// doDELETERequest runs a DELETE request using the given client
// and API endpoint.
func doDELETERequest(
ctx context.Context,
client *Client,
endpoint string,
) error {
req := client.R(ctx)
_, err := coupleAPIErrors(req.Delete(endpoint))
return err
}
// formatAPIPath allows us to safely build an API request with path escaping
func formatAPIPath(format string, args ...any) string {
escapedArgs := make([]any, len(args))
for i, arg := range args {
if typeStr, ok := arg.(string); ok {
arg = url.PathEscape(typeStr)
}
escapedArgs[i] = arg
}
return fmt.Sprintf(format, escapedArgs...)
}
func isNil(i interface{}) bool {
if i == nil {
return true
}
// Check for nil pointers
v := reflect.ValueOf(i)
return v.Kind() == reflect.Ptr && v.IsNil()
}
|