Skip to content

Commit

Permalink
chore: add some comments in snapshot client
Browse files Browse the repository at this point in the history
  • Loading branch information
pseudoyu authored Dec 5, 2023
1 parent 6af0e79 commit 422fbfb
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 0 deletions.
11 changes: 11 additions & 0 deletions provider/snapshot/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"github.com/Khan/genqlient/graphql"
)

// Command to generate the client code in operation.go.
//go:generate go run --mod=mod github.com/Khan/[email protected]

const (
Expand All @@ -18,31 +19,41 @@ const (
ProposalStateClosed = "closed"
)

// Use _ to make sure we implement the interface.
var _ graphql.Doer = (*client)(nil)

// A graphql.Doer that adds the X-API-KEY header to requests.
type client struct {
httpClient *http.Client
apiKey string
}

// Do implements [graphql.Doer].
func (c *client) Do(request *http.Request) (*http.Response, error) {
// add the X-API-KEY header if it's set.
if c.apiKey != "" {
request.Header.Set("X-API-KEY", c.apiKey)
}

// do the request
return c.httpClient.Do(request)
}

// NewClient a function that can be used to configure a [client] with options.
// Options are applied in the order they are passed to the function
func NewClient(endpoint string, options ...Option) (graphql.Client, error) {
// build a default client
instance := client{
httpClient: http.DefaultClient,
}

// Apply options.
for _, option := range options {
if err := option(&instance); err != nil {
return nil, fmt.Errorf("apply option: %w", err)
}
}

// Return the client
return graphql.NewClient(endpoint, &instance), nil
}
2 changes: 2 additions & 0 deletions provider/snapshot/option.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package snapshot

// Option is a function that can be used to configure a [client].
type Option func(client *client) error

// WithAPIKey is an [Option] that can be used to set the X-API-KEY header for requests.
func WithAPIKey(apiKey string) Option {
return func(client *client) error {
client.apiKey = apiKey
Expand Down

0 comments on commit 422fbfb

Please sign in to comment.