Skip to content

Commit

Permalink
Leverage the management client to make api requests in api cmd
Browse files Browse the repository at this point in the history
  • Loading branch information
sergiught committed Mar 17, 2023
1 parent 200ea69 commit e0fbf35
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 9 deletions.
3 changes: 3 additions & 0 deletions internal/auth0/auth0.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ type API struct {
Tenant TenantAPI
User UserAPI
Jobs JobsAPI

HTTPClient HTTPClientAPI
}

func NewAPI(m *management.Management) *API {
Expand All @@ -50,6 +52,7 @@ func NewAPI(m *management.Management) *API {
Tenant: m.Tenant,
User: m.User,
Jobs: m.Job,
HTTPClient: m,
}
}

Expand Down
17 changes: 17 additions & 0 deletions internal/auth0/http_client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package auth0

import (
"net/http"

"github.com/auth0/go-auth0/management"
)

type HTTPClientAPI interface {
// NewRequest returns a new HTTP request.
// If the payload is not nil it will be encoded as JSON.
NewRequest(method, uri string, payload interface{}, options ...management.RequestOption) (*http.Request, error)

// Do triggers an HTTP request and returns an HTTP response,
// handling any context cancellations or timeouts.
Do(req *http.Request) (*http.Response, error)
}
13 changes: 4 additions & 9 deletions internal/cli/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@ import (
"net/url"
"strings"

"github.com/auth0/go-auth0/management"
"github.com/spf13/cobra"

"github.com/auth0/auth0-cli/internal/ansi"
"github.com/auth0/auth0-cli/internal/buildinfo"
"github.com/auth0/auth0-cli/internal/display"
"github.com/auth0/auth0-cli/internal/iostream"
"github.com/auth0/auth0-cli/internal/prompt"
Expand Down Expand Up @@ -131,26 +131,21 @@ func apiCmdRun(cli *cli, inputs *apiCmdInputs) func(cmd *cobra.Command, args []s

var response *http.Response
if err := ansi.Waiting(func() error {
request, err := http.NewRequestWithContext(
cmd.Context(),
request, err := cli.api.HTTPClient.NewRequest(
inputs.Method,
inputs.URL.String(),
inputs.Data,
management.Context(cmd.Context()),
)
if err != nil {
return err
}

accessToken := getAccessToken(cli.config.Tenants[cli.tenant])
request.Header.Set("Authorization", fmt.Sprintf("Bearer %s", accessToken))
request.Header.Set("Content-Type", "application/json")
request.Header.Set("User-Agent", fmt.Sprintf("%s/%s", userAgent, strings.TrimPrefix(buildinfo.Version, "v")))

if cli.debug {
cli.renderer.Infof("[%s]: %s", request.Method, request.URL.String())
}

response, err = http.DefaultClient.Do(request)
response, err = cli.api.HTTPClient.Do(request)
return err
}); err != nil {
return fmt.Errorf("failed to send request: %w", err)
Expand Down

0 comments on commit e0fbf35

Please sign in to comment.