Skip to content

Commit 24f6df9

Browse files
committed
fast fail in APIClient when CI=true and no Access Token
1 parent b02a6d4 commit 24f6df9

1 file changed

Lines changed: 26 additions & 8 deletions

File tree

internal/api/api.go

Lines changed: 26 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -71,9 +71,10 @@ type request struct {
7171

7272
// ClientOpts encapsulates the options given to NewClient.
7373
type ClientOpts struct {
74-
EndpointURL *url.URL
75-
AccessToken string
76-
AdditionalHeaders map[string]string
74+
EndpointURL *url.URL
75+
AccessToken string
76+
AdditionalHeaders map[string]string
77+
RequireAccessToken bool
7778

7879
// Flags are the standard API client flags provided by NewFlags. If nil,
7980
// default values will be used.
@@ -135,15 +136,24 @@ func NewClient(opts ClientOpts) Client {
135136

136137
return &client{
137138
opts: ClientOpts{
138-
EndpointURL: opts.EndpointURL,
139-
AccessToken: opts.AccessToken,
140-
AdditionalHeaders: opts.AdditionalHeaders,
141-
Flags: flags,
142-
Out: opts.Out,
139+
EndpointURL: opts.EndpointURL,
140+
AccessToken: opts.AccessToken,
141+
AdditionalHeaders: opts.AdditionalHeaders,
142+
RequireAccessToken: opts.RequireAccessToken,
143+
Flags: flags,
144+
Out: opts.Out,
143145
},
144146
httpClient: httpClient,
145147
}
146148
}
149+
150+
func (c *client) requireAccessToken() error {
151+
if c.opts.RequireAccessToken && c.opts.AccessToken == "" {
152+
return fmt.Errorf("SRC_ACCESS_TOKEN must be set in CI")
153+
}
154+
155+
return nil
156+
}
147157
func (c *client) NewQuery(query string) Request {
148158
return c.NewRequest(query, nil)
149159
}
@@ -170,6 +180,10 @@ func (c *client) NewHTTPRequest(ctx context.Context, method, p string, body io.R
170180
}
171181

172182
func (c *client) createHTTPRequest(ctx context.Context, method, p string, body io.Reader) (*http.Request, error) {
183+
if err := c.requireAccessToken(); err != nil {
184+
return nil, err
185+
}
186+
173187
// Can't use c.opts.EndpointURL.JoinPath(p) here because `p` could contain a query string
174188
req, err := http.NewRequestWithContext(ctx, method, c.opts.EndpointURL.String()+"/"+p, body)
175189
if err != nil {
@@ -199,6 +213,10 @@ func (c *client) createHTTPRequest(ctx context.Context, method, p string, body i
199213
}
200214

201215
func (r *request) do(ctx context.Context, result any) (bool, error) {
216+
if err := r.client.requireAccessToken(); err != nil {
217+
return false, err
218+
}
219+
202220
if *r.client.opts.Flags.getCurl {
203221
curl, err := r.curlCmd()
204222
if err != nil {

0 commit comments

Comments
 (0)