-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathapi.go
More file actions
86 lines (71 loc) · 2.15 KB
/
api.go
File metadata and controls
86 lines (71 loc) · 2.15 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
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
package cloudapi
import (
"context"
"errors"
"fmt"
"io"
"math"
"net/url"
k6cloud "github.com/grafana/k6-cloud-openapi-client-go/k6"
)
// ListProjects retrieves the list of projects for the configured stack.
func (c *Client) ListProjects() (*k6cloud.ProjectListResponse, error) {
// Bound checking stackID (int64) to support using it as an int32 in calls
// to the API.
if c.stackID < math.MinInt32 || c.stackID > math.MaxInt32 {
return nil, fmt.Errorf("stack ID %d overflows int32", c.stackID)
}
ctx := context.WithValue(context.Background(), k6cloud.ContextAccessToken, c.token)
req := c.apiClient.ProjectsAPI.
ProjectsList(ctx).
XStackId(int32(c.stackID))
resp, httpRes, rerr := req.Execute()
defer func() {
if httpRes != nil {
_, _ = io.Copy(io.Discard, httpRes.Body)
_ = httpRes.Body.Close()
}
}()
if rerr != nil {
var apiErr *k6cloud.GenericOpenAPIError
if !errors.As(rerr, &apiErr) {
return nil, fmt.Errorf("failed to list projects: %w", rerr)
}
}
if err := CheckResponse(httpRes); err != nil {
return nil, fmt.Errorf("failed to list projects: %w", err)
}
return resp, nil
}
// ValidateToken calls the endpoint to validate the Client's token and returns the result.
func (c *Client) ValidateToken(stackURL string) (_ *k6cloud.AuthenticationResponse, err error) {
if stackURL == "" {
return nil, errors.New("stack URL is required to validate token")
}
if _, err := url.Parse(stackURL); err != nil {
return nil, fmt.Errorf("invalid stack URL: %w", err)
}
ctx := context.WithValue(context.Background(), k6cloud.ContextAccessToken, c.token)
req := c.apiClient.AuthorizationAPI.
Auth(ctx).
XStackUrl(stackURL)
resp, httpRes, rerr := req.Execute()
defer func() {
if httpRes != nil {
_, _ = io.Copy(io.Discard, httpRes.Body)
if cerr := httpRes.Body.Close(); cerr != nil && err == nil {
err = cerr
}
}
}()
if rerr != nil {
var apiErr *k6cloud.GenericOpenAPIError
if !errors.As(rerr, &apiErr) {
return nil, fmt.Errorf("failed to validate token: %w", rerr)
}
}
if err := CheckResponse(httpRes); err != nil {
return nil, fmt.Errorf("failed to validate token: %w", err)
}
return resp, err
}