forked from CircleCI-Public/circleci-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
44 lines (36 loc) · 1.31 KB
/
client.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package client
import (
"context"
"fmt"
"github.com/CircleCI-Public/circleci-cli/logger"
"github.com/CircleCI-Public/circleci-cli/version"
"github.com/machinebox/graphql"
)
// NewClient returns a reference to a Client.
// We also call graphql.NewClient to initialize a new GraphQL Client.
// Then we pass the Logger originally constructed as cmd.Logger.
func NewClient(endpoint string, logger *logger.Logger) *graphql.Client {
client := graphql.NewClient(endpoint)
client.Log = func(s string) {
logger.Debug(fmt.Sprintf("[machinebox/graphql] %s", s))
}
return client
}
// NewAuthorizedRequest returns a new GraphQL request with the
// authorization headers set for CircleCI auth.
func NewAuthorizedRequest(token, query string) *graphql.Request {
req := graphql.NewRequest(query)
req.Header.Set("Authorization", token)
req.Header.Set("User-Agent", version.UserAgent())
return req
}
// Run will construct a request using graphql.NewRequest.
// Then it will execute the given query using graphql.Client.Run.
// This function will return the unmarshalled response as JSON.
func Run(client *graphql.Client, token, query string) (map[string]interface{}, error) {
req := NewAuthorizedRequest(token, query)
ctx := context.Background()
var resp map[string]interface{}
err := client.Run(ctx, req, &resp)
return resp, err
}