-
Notifications
You must be signed in to change notification settings - Fork 2
/
api.go
55 lines (44 loc) · 1.01 KB
/
api.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
package utils
import (
"context"
"fmt"
"io"
"net/http"
"github.com/apono-io/apono-cli/pkg/aponoapi"
"github.com/apono-io/apono-cli/pkg/clientapi"
)
func GetAllPages[T any](
ctx context.Context,
client *aponoapi.AponoClient,
nextPageFunc func(context.Context, *aponoapi.AponoClient, int32) ([]T, *clientapi.PaginationClientInfoModel, error),
) ([]T, error) {
var result []T
skip := 0
for {
resp, pagination, err := nextPageFunc(ctx, client, int32(skip))
if err != nil {
return nil, err
}
result = append(result, resp...)
skip += int(pagination.Limit)
hasNextPage := int(pagination.Limit) <= len(resp)
if !hasNextPage {
break
}
}
return result, nil
}
func ReturnAPIResponseError(resp *http.Response) error {
defer func() {
_ = resp.Body.Close()
}()
if resp.StatusCode >= 400 && resp.StatusCode <= 499 {
bodyBytes, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
bodyString := string(bodyBytes)
return fmt.Errorf("api error: %s", bodyString)
}
return nil
}