Skip to content

Commit

Permalink
Add graphql client wrapper package
Browse files Browse the repository at this point in the history
Hook up client and query command to logger
  • Loading branch information
Zachary Scott committed Jun 5, 2018
1 parent 4a7489c commit f29be32
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 23 deletions.
37 changes: 37 additions & 0 deletions client/client.go
Original file line number Diff line number Diff line change
@@ -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
}
31 changes: 8 additions & 23 deletions cmd/query.go
Original file line number Diff line number Diff line change
@@ -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"
)
Expand All @@ -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 {
Expand All @@ -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")
}

0 comments on commit f29be32

Please sign in to comment.