Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow providing a custom request factory #73

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion graphql.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,16 @@ import (
type Client struct {
url string // GraphQL server URL.
httpClient *http.Client
RequestFactory func(method, url string, body io.Reader) (*http.Request, error)
}

// defaultRequestFactory creates JSON requests
func defaultRequestFactory(method, url string, body io.Reader) (*http.Request, error) {
req, err := http.NewRequest(method, url, body)
if err == nil {
req.Header.Set("Content-Type", "application/json")
}
return req, err
}

// NewClient creates a GraphQL client targeting the specified GraphQL server URL.
Expand All @@ -27,6 +37,7 @@ func NewClient(url string, httpClient *http.Client) *Client {
return &Client{
url: url,
httpClient: httpClient,
RequestFactory: defaultRequestFactory,
}
}

Expand Down Expand Up @@ -65,7 +76,11 @@ func (c *Client) do(ctx context.Context, op operationType, v interface{}, variab
if err != nil {
return err
}
resp, err := ctxhttp.Post(ctx, c.httpClient, c.url, "application/json", &buf)
req, err := c.RequestFactory(http.MethodPost, c.url, &buf)
if err != nil {
return err
}
resp, err := ctxhttp.Do(ctx, c.httpClient, req)
if err != nil {
return err
}
Expand Down