refactor promethueus package into sub packages (#43634)

This commit is contained in:
Travis Patterson
2022-01-04 07:22:33 -07:00
committed by GitHub
parent 567e2b5fd8
commit c4c05a5b71
7 changed files with 117 additions and 102 deletions
+53
View File
@@ -0,0 +1,53 @@
package client
import (
"strings"
"github.com/grafana/grafana/pkg/tsdb/prometheus/middleware"
sdkhttpclient "github.com/grafana/grafana-plugin-sdk-go/backend/httpclient"
"github.com/grafana/grafana/pkg/infra/httpclient"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/prometheus/client_golang/api"
apiv1 "github.com/prometheus/client_golang/api/prometheus/v1"
)
func Create(url string, httpOpts sdkhttpclient.Options, clientProvider httpclient.Provider, jsonData map[string]interface{}, plog log.Logger) (apiv1.API, error) {
customParamsMiddleware := middleware.CustomQueryParameters(plog)
middlewares := []sdkhttpclient.Middleware{customParamsMiddleware}
if shouldForceGet(jsonData) {
middlewares = append(middlewares, middleware.ForceHttpGet(plog))
}
httpOpts.Middlewares = middlewares
roundTripper, err := clientProvider.GetTransport(httpOpts)
if err != nil {
return nil, err
}
cfg := api.Config{
Address: url,
RoundTripper: roundTripper,
}
client, err := api.NewClient(cfg)
if err != nil {
return nil, err
}
return apiv1.NewAPI(client), nil
}
func shouldForceGet(settingsJson map[string]interface{}) bool {
methodInterface, exists := settingsJson["httpMethod"]
if !exists {
return false
}
method, ok := methodInterface.(string)
if !ok {
return false
}
return strings.ToLower(method) == "get"
}
@@ -0,0 +1,47 @@
package client
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestForceGet(t *testing.T) {
t.Run("With nil jsonOpts, should not force get-method", func(t *testing.T) {
var jsonOpts map[string]interface{}
require.False(t, shouldForceGet(jsonOpts))
})
t.Run("With empty jsonOpts, should not force get-method", func(t *testing.T) {
jsonOpts := make(map[string]interface{})
require.False(t, shouldForceGet(jsonOpts))
})
t.Run("With httpMethod=nil, should not not force get-method", func(t *testing.T) {
jsonOpts := map[string]interface{}{
"httpMethod": nil,
}
require.False(t, shouldForceGet(jsonOpts))
})
t.Run("With httpMethod=post, should not force get-method", func(t *testing.T) {
jsonOpts := map[string]interface{}{
"httpMethod": "POST",
}
require.False(t, shouldForceGet(jsonOpts))
})
t.Run("With httpMethod=get, should force get-method", func(t *testing.T) {
jsonOpts := map[string]interface{}{
"httpMethod": "get",
}
require.True(t, shouldForceGet(jsonOpts))
})
t.Run("With httpMethod=GET, should force get-method", func(t *testing.T) {
jsonOpts := map[string]interface{}{
"httpMethod": "GET",
}
require.True(t, shouldForceGet(jsonOpts))
})
}