work on eia client

This commit is contained in:
Ryan McGuire 2024-11-19 08:42:18 -05:00
parent 9af155dbde
commit 55f6086bd4
4 changed files with 74 additions and 55 deletions

View File

@ -3,6 +3,7 @@ package list
import ( import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
eiaapi "gitea.libretechconsulting.com/50W/eia-api-go/api"
"gitea.libretechconsulting.com/50W/eia-api-go/cmd/eia-client/internal/util" "gitea.libretechconsulting.com/50W/eia-api-go/cmd/eia-client/internal/util"
) )
@ -16,6 +17,7 @@ var ListCmd = &cobra.Command{
func runListCmd(cmd *cobra.Command, _ []string) { func runListCmd(cmd *cobra.Command, _ []string) {
logger := util.Logger(cmd) logger := util.Logger(cmd)
client, err := util.Client(cmd) client, err := util.Client(cmd)
if err != nil { if err != nil {
logger.Fatal().Err(err).Send() logger.Fatal().Err(err).Send()
@ -23,10 +25,11 @@ func runListCmd(cmd *cobra.Command, _ []string) {
ctx, cncl := util.RequestCtx(cmd) ctx, cncl := util.RequestCtx(cmd)
defer cncl() defer cncl()
resp, err := client.GetV2(ctx) resp, err := client.GetV2AeoRoute1DataWithResponse(ctx, "2023", &eiaapi.GetV2AeoRoute1DataParams{})
if err != nil { if err != nil {
logger.Err(err).Send() logger.Error().Bytes("body", resp.Body)
logger.Fatal().Err(err).Send()
} }
logger.Debug().Any("resp", resp).Send() logger.Info().Str("resp", string(resp.Body)).Send()
} }

View File

@ -51,6 +51,10 @@ func PreRun(cmd *cobra.Command, _ []string) {
Timestamp().Logger().Level(*util.GetLogLevel(cmd)) Timestamp().Logger().Level(*util.GetLogLevel(cmd))
util.SetLogger(cmd, &logger) util.SetLogger(cmd, &logger)
util.Logger(cmd).Debug().
Str("logLevel", util.Logger(cmd).GetLevel().String()).
Msg("logging configured")
} }
// Execute adds all child commands to the root command and sets flags appropriately. // Execute adds all child commands to the root command and sets flags appropriately.
@ -70,10 +74,10 @@ func init() {
cobra.EnableTraverseRunHooks = true cobra.EnableTraverseRunHooks = true
// Handle command flags // Handle command flags
rootCmd.PersistentFlags().StringP(util.FLAG_LOG_LEVEL, "l", util.DefaultLogLevel.String(), rootCmd.PersistentFlags().StringP(util.FLAG_LOG_LEVEL, "l", "",
"Log Level, or set "+util.ENV_LOG_LEVEL+" in environment") "Log Level, or set "+util.ENV_LOG_LEVEL+" in environment")
rootCmd.PersistentFlags().StringP(util.FLAG_API_LOG_LEVEL, "L", util.DefAPILogLevel.String(), rootCmd.PersistentFlags().StringP(util.FLAG_API_LOG_LEVEL, "L", "",
"Log Level for EIA API Middleware, or set "+util.ENV_API_LOG_LEVEL+" in environment") "Log Level for EIA API Middleware, or set "+util.ENV_API_LOG_LEVEL+" in environment")
rootCmd.PersistentFlags().StringP(util.FLAG_APIKEY, rootCmd.PersistentFlags().StringP(util.FLAG_APIKEY,

View File

@ -1,6 +1,7 @@
package util package util
import ( import (
"fmt"
"os" "os"
"github.com/rs/zerolog" "github.com/rs/zerolog"
@ -18,57 +19,61 @@ func SetLogger(cmd *cobra.Command, logger *zerolog.Logger) {
} }
func GetLogLevel(cmd *cobra.Command) *zerolog.Level { func GetLogLevel(cmd *cobra.Command) *zerolog.Level {
var level zerolog.Level setLevel, err := GetStrFlagOrEnv(cmd, FLAG_LOG_LEVEL, ENV_LOG_LEVEL)
var err error if err != nil || setLevel == "" {
if envLevel := os.Getenv(ENV_LOG_LEVEL); envLevel != "" { Logger(cmd).Warn().Err(err).
level, err = zerolog.ParseLevel(envLevel) Str("defaultLogLevel", DefAPILogLevel.String()).
if err != nil { Msg("no log level set, using default")
Logger(cmd).Err(err). return &DefaultLogLevel
Str("envLogLevel", envLevel).
Str("envVar", ENV_LOG_LEVEL).
Str("defaultLevel", DefaultLogLevel.String()).
Msg("Invalid log level in environment, using default")
level = DefaultLogLevel
}
} }
if flagLevel, err := cmd.Flags().GetString(FLAG_LOG_LEVEL); err == nil { level, err := zerolog.ParseLevel(setLevel)
level, err = zerolog.ParseLevel(flagLevel) if err != nil {
if err != nil { Logger(cmd).Err(err).
Logger(cmd).Err(err). Str("logLevel", setLevel).
Str("flagLogLevel", flagLevel). Str("defaultLevel", DefaultLogLevel.String()).
Str("defaultLevel", DefaultLogLevel.String()). Msg("Invalid log level, using default")
Msg("Invalid log level in command flag, using default") level = DefaultLogLevel
level = DefaultLogLevel
}
} }
return &level return &level
} }
func GetAPILogLevel(cmd *cobra.Command) *zerolog.Level { func GetAPILogLevel(cmd *cobra.Command) *zerolog.Level {
var level zerolog.Level setLevel, err := GetStrFlagOrEnv(cmd, FLAG_API_LOG_LEVEL, ENV_API_LOG_LEVEL)
var err error if err != nil || setLevel == "" {
if envLevel := os.Getenv(ENV_API_LOG_LEVEL); envLevel != "" { Logger(cmd).Warn().Err(err).
level, err = zerolog.ParseLevel(envLevel) Str("defaultLogLevel", DefAPILogLevel.String()).
if err != nil { Msg("no API log level set, using default")
Logger(cmd).Err(err). return &DefAPILogLevel
Str("envLogLevel", envLevel).
Str("envVar", ENV_API_LOG_LEVEL).
Str("defaultLevel", DefAPILogLevel.String()).
Msg("Invalid API log level in environment, using default")
level = DefAPILogLevel
}
} }
if flagLevel, err := cmd.Flags().GetString(FLAG_API_LOG_LEVEL); err == nil { level, err := zerolog.ParseLevel(setLevel)
level, err = zerolog.ParseLevel(flagLevel) if err != nil {
if err != nil { Logger(cmd).Err(err).
Logger(cmd).Err(err). Str("logLevel", setLevel).
Str("flagLogLevel", flagLevel). Str("defaultLevel", DefAPILogLevel.String()).
Str("defaultLevel", DefAPILogLevel.String()). Msg("Invalid API log level, using default")
Msg("Invalid API log level in command flag, using default") level = DefAPILogLevel
level = DefAPILogLevel
}
} }
return &level return &level
} }
// If set and not empty, returns the flag value
// Otherwise, returns the env value, empty or not
func GetStrFlagOrEnv(cmd *cobra.Command, flagName string, envName string) (string, error) {
flag, err := cmd.Flags().GetString(flagName)
if err != nil {
return "", err
} else if flag != "" {
return flag, nil
}
envVal, set := os.LookupEnv(envName)
if !set {
return envVal, fmt.Errorf("environment variable %s not set", envName)
}
return envVal, nil
}

View File

@ -29,7 +29,7 @@ type Client struct {
ctx context.Context ctx context.Context
apiKey string apiKey string
healthCheckTimeout time.Duration healthCheckTimeout time.Duration
*eiaapi.Client *eiaapi.ClientWithResponses
} }
type ClientOpts struct { type ClientOpts struct {
@ -56,11 +56,18 @@ func NewClient(opts *ClientOpts) (*Client, error) {
// Injects Authorization: Bearer <APIKey> header into // Injects Authorization: Bearer <APIKey> header into
// outbound API calls // outbound API calls
basicAuth, err := securityprovider.NewSecurityProviderBearerToken(opts.APIKey) // basicAuth, err := securityprovider.NewSecurityProviderBearerToken(opts.APIKey)
// if err != nil {
// return nil, err
// }
// middlewares = append(middlewares, eiaapi.WithRequestEditorFn(basicAuth.Intercept))
// Injects API key as query parameter: ?api_key=<apiKey>
paramAuth, err := securityprovider.NewSecurityProviderApiKey("query", "api_key", opts.APIKey)
if err != nil { if err != nil {
return nil, err return nil, err
} }
middlewares = append(middlewares, eiaapi.WithRequestEditorFn(basicAuth.Intercept)) middlewares = append(middlewares, eiaapi.WithRequestEditorFn(paramAuth.Intercept))
// Logging middleware, if logger is given // Logging middleware, if logger is given
if opts.Logger != nil { if opts.Logger != nil {
@ -73,15 +80,15 @@ func NewClient(opts *ClientOpts) (*Client, error) {
eiaapi.WithRequestEditorFn(newLoggingMiddleware(opts.Logger, logLevel))) eiaapi.WithRequestEditorFn(newLoggingMiddleware(opts.Logger, logLevel)))
} }
client, err := eiaapi.NewClient(baseURL, slices.Clip(middlewares)...) client, err := eiaapi.NewClientWithResponses(baseURL, slices.Clip(middlewares)...)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return &Client{ return &Client{
apiKey: opts.APIKey, apiKey: opts.APIKey,
ctx: opts.Context, ctx: opts.Context,
healthCheckTimeout: hcTimeout, healthCheckTimeout: hcTimeout,
Client: client, ClientWithResponses: client,
}, nil }, nil
} }