From f29be3248f6334540541764bf91f7181221102c8 Mon Sep 17 00:00:00 2001 From: Zachary Scott Date: Wed, 6 Jun 2018 00:46:32 +0900 Subject: [PATCH] Add graphql client wrapper package Hook up client and query command to logger --- client/client.go | 37 +++++++++++++++++++++++++++++++++++++ cmd/query.go | 31 ++++++++----------------------- 2 files changed, 45 insertions(+), 23 deletions(-) create mode 100644 client/client.go diff --git a/client/client.go b/client/client.go new file mode 100644 index 000000000..b66298672 --- /dev/null +++ b/client/client.go @@ -0,0 +1,37 @@ +package client + +import ( + "context" + + "github.com/circleci/circleci-cli/logger" + "github.com/machinebox/graphql" +) + +type Client struct { + host string + token string + client *graphql.Client + logger *logger.Logger +} + +func NewClient(host string, token string, logger *logger.Logger) *Client { + return &Client{ + host, + token, + graphql.NewClient(host + "/graphql"), + logger, + } +} + +func (c *Client) Run(query string) (map[string]interface{}, error) { + req := graphql.NewRequest(query) + req.Header.Set("Authorization", c.token) + + ctx := context.Background() + var resp map[string]interface{} + + // TODO: fix wrapping logs with + c.logger.Info("Querying ", c.host, " with:\n\n", query, "\n\n") + err := c.client.Run(ctx, req, &resp) + return resp, err +} diff --git a/cmd/query.go b/cmd/query.go index cb28b0eda..0c9f3b80e 100644 --- a/cmd/query.go +++ b/cmd/query.go @@ -1,12 +1,9 @@ package cmd import ( - "context" "encoding/json" - "fmt" - "log" - "github.com/machinebox/graphql" + "github.com/circleci/circleci-cli/client" "github.com/spf13/cobra" "github.com/spf13/viper" ) @@ -18,9 +15,7 @@ var queryCmd = &cobra.Command{ } func query(cmd *cobra.Command, args []string) { - host := viper.GetString("host") - token := viper.GetString("token") - client := graphql.NewClient(host + "/graphql") + client := client.NewClient(viper.GetString("host"), viper.GetString("token"), Logger) query := ` query IntrospectionQuery { @@ -47,21 +42,11 @@ func query(cmd *cobra.Command, args []string) { } }` - req := graphql.NewRequest(query) - req.Header.Set("Authorization", token) - - ctx := context.Background() - var resp map[string]interface{} - - fmt.Print("Querying ", host, " with:\n\n", query, "\n\n") - if err := client.Run(ctx, req, &resp); err != nil { - log.Fatal(err) - } - + resp, err := client.Run(query) + Logger.FatalOnError("Something happend", err) b, err := json.MarshalIndent(resp, "", " ") - if err != nil { - log.Fatalln("Could not parse graphql response", err.Error()) - } - fmt.Print("Result: \n\n") - fmt.Println(string(b)) + Logger.FatalOnError("Could not parse graphql response", err) + + Logger.Info("Result: \n\n") + Logger.Info(string(b) + "\n") }