github.com/ouraigua/jenkins-library@v0.0.0-20231028010029-fbeaf2f3aa9b/pkg/apim/APIMUtility.go (about)

     1  package apim
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"strings"
     7  
     8  	"github.com/SAP/jenkins-library/pkg/cpi"
     9  	piperhttp "github.com/SAP/jenkins-library/pkg/http"
    10  	"github.com/SAP/jenkins-library/pkg/xsuaa"
    11  	"github.com/pasztorpisti/qs"
    12  	"github.com/pkg/errors"
    13  )
    14  
    15  // Utils for apim
    16  type Utils interface {
    17  	InitAPIM() error
    18  	IsPayloadJSON() bool
    19  }
    20  
    21  // OdataUtils for apim
    22  type OdataUtils interface {
    23  	MakeOdataQuery() (string, error)
    24  }
    25  
    26  // OdataParameters struct
    27  type OdataParameters struct {
    28  	Filter, Search          string
    29  	Top, Skip               int
    30  	Orderby, Select, Expand string
    31  }
    32  
    33  // Bundle struct
    34  type Bundle struct {
    35  	APIServiceKey, Host, Payload string
    36  	Client                       piperhttp.Sender
    37  }
    38  
    39  // InitAPIM() fumnction initialize APIM bearer token for API access
    40  func (apim *Bundle) InitAPIM() error {
    41  	serviceKey, err := cpi.ReadCpiServiceKey(apim.APIServiceKey)
    42  	if err != nil {
    43  		return err
    44  	}
    45  	apim.Host = serviceKey.OAuth.Host
    46  	httpClient := apim.Client
    47  	clientOptions := piperhttp.ClientOptions{}
    48  	x := xsuaa.XSUAA{
    49  		OAuthURL:     serviceKey.OAuth.OAuthTokenProviderURL,
    50  		ClientID:     serviceKey.OAuth.ClientID,
    51  		ClientSecret: serviceKey.OAuth.ClientSecret,
    52  	}
    53  	token, tokenErr := x.GetBearerToken()
    54  
    55  	if tokenErr != nil {
    56  		return errors.Wrap(tokenErr, "failed to fetch Bearer Token")
    57  	}
    58  	clientOptions.Token = fmt.Sprintf("Bearer %s", token.AccessToken)
    59  	httpClient.SetOptions(clientOptions)
    60  	return nil
    61  }
    62  
    63  // IsJSON checks given string is valid json or not
    64  func (apim *Bundle) IsPayloadJSON() bool {
    65  	var js json.RawMessage
    66  	return json.Unmarshal([]byte(apim.Payload), &js) == nil
    67  }
    68  
    69  func (odataFilters *OdataParameters) MakeOdataQuery() (string, error) {
    70  
    71  	customMarshaler := qs.NewMarshaler(&qs.MarshalOptions{
    72  		DefaultMarshalPresence: qs.OmitEmpty,
    73  	})
    74  	values, encodeErr := customMarshaler.Marshal(odataFilters)
    75  	if encodeErr == nil && len(values) > 0 {
    76  		values = "?" + strings.ReplaceAll(values, "&", "&$")
    77  	}
    78  	return values, encodeErr
    79  }