|
| 1 | +package genericclient |
| 2 | + |
| 3 | +import ( |
| 4 | + "github.com/stackitcloud/stackit-cli/internal/pkg/auth" |
| 5 | + "github.com/stackitcloud/stackit-cli/internal/pkg/errors" |
| 6 | + "github.com/stackitcloud/stackit-cli/internal/pkg/print" |
| 7 | + "github.com/stackitcloud/stackit-cli/internal/pkg/utils" |
| 8 | + sdkConfig "github.com/stackitcloud/stackit-sdk-go/core/config" |
| 9 | +) |
| 10 | + |
| 11 | +type CreateApiClient[T any] func(opts ...sdkConfig.ConfigurationOption) (T, error) |
| 12 | + |
| 13 | +// ConfigureClientGeneric contains the generic code which needs to be executed in order to configure the api client. |
| 14 | +// TODO: region parameter will be removed when every API implemented the new region |
| 15 | +func ConfigureClientGeneric[T any](p *print.Printer, cliVersion, customEndpoint, region string, createApiClient CreateApiClient[T]) (T, error) { |
| 16 | + // return value if an error happens |
| 17 | + var zero T |
| 18 | + authCfgOption, err := auth.AuthenticationConfig(p, auth.AuthorizeUser) |
| 19 | + if err != nil { |
| 20 | + p.Debug(print.ErrorLevel, "configure authentication: %v", err) |
| 21 | + return zero, &errors.AuthError{} |
| 22 | + } |
| 23 | + cfgOptions := []sdkConfig.ConfigurationOption{ |
| 24 | + utils.UserAgentConfigOption(cliVersion), |
| 25 | + authCfgOption, |
| 26 | + } |
| 27 | + |
| 28 | + if customEndpoint != "" { |
| 29 | + cfgOptions = append(cfgOptions, sdkConfig.WithEndpoint(customEndpoint)) |
| 30 | + } |
| 31 | + |
| 32 | + // TODO: this will be removed when every API implemented the new region |
| 33 | + if region != "" { |
| 34 | + cfgOptions = append(cfgOptions, authCfgOption, sdkConfig.WithRegion(region)) |
| 35 | + } |
| 36 | + |
| 37 | + if p.IsVerbosityDebug() { |
| 38 | + cfgOptions = append(cfgOptions, |
| 39 | + sdkConfig.WithMiddleware(print.RequestResponseCapturer(p, nil)), |
| 40 | + ) |
| 41 | + } |
| 42 | + |
| 43 | + apiClient, err := createApiClient(cfgOptions...) |
| 44 | + if err != nil { |
| 45 | + p.Debug(print.ErrorLevel, "create new API client: %v", err) |
| 46 | + return zero, &errors.AuthError{} |
| 47 | + } |
| 48 | + |
| 49 | + return apiClient, nil |
| 50 | +} |
0 commit comments