github.com/newrelic/newrelic-client-go@v1.1.0/pkg/accounts/accounts.go (about)

     1  // Package accounts provides a programmatic API for interacting with New Relic accounts.
     2  package accounts
     3  
     4  import (
     5  	"context"
     6  
     7  	"github.com/newrelic/newrelic-client-go/internal/http"
     8  	"github.com/newrelic/newrelic-client-go/pkg/config"
     9  	"github.com/newrelic/newrelic-client-go/pkg/logging"
    10  )
    11  
    12  // Accounts is used to interact with New Relic accounts.
    13  type Accounts struct {
    14  	client http.Client
    15  	logger logging.Logger
    16  }
    17  
    18  // New returns a new client for interacting with New Relic accounts.
    19  func New(config config.Config) Accounts {
    20  	return Accounts{
    21  		client: http.NewClient(config),
    22  		logger: config.GetLogger(),
    23  	}
    24  }
    25  
    26  // ListAccountsParams represents the input parameters for the ListAcounts method.
    27  type ListAccountsParams struct {
    28  	Scope *RegionScope
    29  }
    30  
    31  // ListAccounts lists the accounts this user is authorized to view.
    32  func (e *Accounts) ListAccounts(params ListAccountsParams) ([]AccountOutline, error) {
    33  	return e.ListAccountsWithContext(context.Background(), params)
    34  }
    35  
    36  // ListAccountsWithContext lists the accounts this user is authorized to view.
    37  func (e *Accounts) ListAccountsWithContext(ctx context.Context, params ListAccountsParams) ([]AccountOutline, error) {
    38  	resp := accountsResponse{}
    39  	vars := map[string]interface{}{
    40  		"accountId": params.Scope,
    41  	}
    42  
    43  	if err := e.client.NerdGraphQueryWithContext(ctx, listAccountsQuery, vars, &resp); err != nil {
    44  		return nil, err
    45  	}
    46  
    47  	return resp.Actor.Accounts, nil
    48  }
    49  
    50  type accountsResponse struct {
    51  	Actor struct {
    52  		Accounts []AccountOutline
    53  	}
    54  }
    55  
    56  const (
    57  	accountsSchemaFields = `
    58  		name
    59  		id
    60  	`
    61  
    62  	listAccountsQuery = `query($scope: RegionScope) { actor { accounts(scope: $scope) {
    63  		` + accountsSchemaFields +
    64  		` } } }`
    65  )