Skip to content

Commit 77b4c49

Browse files
Add default values for GraphQL variables (#224)
1 parent 7bbac15 commit 77b4c49

File tree

1 file changed

+16
-4
lines changed

1 file changed

+16
-4
lines changed

pkg/graphql/client/client.go

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ import (
2929
"github.com/apache/skywalking-cli/pkg/logger"
3030
)
3131

32+
// newClient creates a new GraphQL client with configuration from context.
3233
func newClient(ctx context.Context) *graphql.Client {
3334
options := []graphql.ClientOption{}
3435

@@ -40,7 +41,8 @@ func newClient(ctx context.Context) *graphql.Client {
4041
options = append(options, graphql.WithHTTPClient(httpClient))
4142
}
4243

43-
client := graphql.NewClient(ctx.Value(contextkey.BaseURL{}).(string), options...)
44+
baseURL := getValue(ctx, contextkey.BaseURL{}, "http://127.0.0.1:12800/graphql")
45+
client := graphql.NewClient(baseURL, options...)
4446
client.Log = func(msg string) {
4547
logger.Log.Debugln(msg)
4648
}
@@ -49,9 +51,10 @@ func newClient(ctx context.Context) *graphql.Client {
4951

5052
// ExecuteQuery executes the `request` and parse to the `response`, returning `error` if there is any.
5153
func ExecuteQuery(ctx context.Context, request *graphql.Request, response any) error {
52-
username := ctx.Value(contextkey.Username{}).(string)
53-
password := ctx.Value(contextkey.Password{}).(string)
54-
authorization := ctx.Value(contextkey.Authorization{}).(string)
54+
username := getValue(ctx, contextkey.Username{}, "")
55+
password := getValue(ctx, contextkey.Password{}, "")
56+
authorization := getValue(ctx, contextkey.Authorization{}, "")
57+
5558
if authorization == "" && username != "" && password != "" {
5659
authorization = "Basic " + base64.StdEncoding.EncodeToString([]byte(username+":"+password))
5760
}
@@ -63,3 +66,12 @@ func ExecuteQuery(ctx context.Context, request *graphql.Request, response any) e
6366
err := client.Run(ctx, request, response)
6467
return err
6568
}
69+
70+
// getValue safely extracts a value from the context.
71+
func getValue[T any](ctx context.Context, key any, defaultValue T) T {
72+
val := ctx.Value(key)
73+
if v, ok := val.(T); ok {
74+
return v
75+
}
76+
return defaultValue
77+
}

0 commit comments

Comments
 (0)