|
| 1 | +package graphqlclient |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "context" |
| 6 | + "encoding/json" |
| 7 | + "fmt" |
| 8 | + "io" |
| 9 | + "net/http" |
| 10 | +) |
| 11 | + |
| 12 | +// Client sends GraphQL requests over HTTP to a single endpoint. It holds |
| 13 | +// persistent headers (e.g. auth tokens) and an optional custom http.Client. |
| 14 | +type Client struct { |
| 15 | + endpoint string |
| 16 | + httpClient *http.Client |
| 17 | + headers map[string]string |
| 18 | +} |
| 19 | + |
| 20 | +// ClientOption is a functional option for configuring a Client at creation time. |
| 21 | +type ClientOption func(*Client) |
| 22 | + |
| 23 | +// NewClient creates a new GraphQL client pointed at the given endpoint. |
| 24 | +func NewClient(endpoint string, opts ...ClientOption) *Client { |
| 25 | + c := &Client{ |
| 26 | + endpoint: endpoint, |
| 27 | + httpClient: http.DefaultClient, |
| 28 | + headers: make(map[string]string), |
| 29 | + } |
| 30 | + for _, opt := range opts { |
| 31 | + opt(c) |
| 32 | + } |
| 33 | + return c |
| 34 | +} |
| 35 | + |
| 36 | +// WithHTTPClient sets the HTTP client |
| 37 | +func WithHTTPClient(httpClient *http.Client) ClientOption { |
| 38 | + return func(c *Client) { |
| 39 | + c.httpClient = httpClient |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +// WithHeader adds a header to all requests |
| 44 | +func WithHeader(key, value string) ClientOption { |
| 45 | + return func(c *Client) { |
| 46 | + c.headers[key] = value |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +// WithHeaders adds multiple headers to all requests |
| 51 | +func WithHeaders(headers map[string]string) ClientOption { |
| 52 | + return func(c *Client) { |
| 53 | + for key, value := range headers { |
| 54 | + c.headers[key] = value |
| 55 | + } |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +// WithAuthToken adds an authorization bearer token |
| 60 | +func WithAuthToken(token string) ClientOption { |
| 61 | + return func(c *Client) { |
| 62 | + c.headers["Authorization"] = "Bearer " + token |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +type graphQLRequest struct { |
| 67 | + Query string `json:"query"` |
| 68 | + Variables map[string]interface{} `json:"variables,omitempty"` |
| 69 | +} |
| 70 | + |
| 71 | +// GraphQLError represents a single error entry returned in a GraphQL response. |
| 72 | +type GraphQLError struct { |
| 73 | + Message string `json:"message"` |
| 74 | + Locations []GraphQLErrorLocation `json:"locations,omitempty"` |
| 75 | + Path []interface{} `json:"path,omitempty"` |
| 76 | + Extensions map[string]interface{} `json:"extensions,omitempty"` |
| 77 | +} |
| 78 | + |
| 79 | +// GraphQLErrorLocation represents the location of a GraphQL error |
| 80 | +type GraphQLErrorLocation struct { |
| 81 | + Line int `json:"line"` |
| 82 | + Column int `json:"column"` |
| 83 | +} |
| 84 | + |
| 85 | +// Error implements the error interface |
| 86 | +func (e GraphQLError) Error() string { |
| 87 | + return e.Message |
| 88 | +} |
| 89 | + |
| 90 | +type graphQLResponse struct { |
| 91 | + Data json.RawMessage `json:"data"` |
| 92 | + Errors []GraphQLError `json:"errors,omitempty"` |
| 93 | +} |
| 94 | + |
| 95 | +// GraphQLErrors is a slice of GraphQLError that implements the error interface. |
| 96 | +type GraphQLErrors []GraphQLError |
| 97 | + |
| 98 | +// Error implements the error interface |
| 99 | +func (e GraphQLErrors) Error() string { |
| 100 | + if len(e) == 0 { |
| 101 | + return "" |
| 102 | + } |
| 103 | + if len(e) == 1 { |
| 104 | + return e[0].Message |
| 105 | + } |
| 106 | + var msgs []string |
| 107 | + for _, err := range e { |
| 108 | + msgs = append(msgs, err.Message) |
| 109 | + } |
| 110 | + return fmt.Sprintf("multiple errors: %v", msgs) |
| 111 | +} |
| 112 | + |
| 113 | +// Execute sends a GraphQL request to the configured endpoint. |
| 114 | +func (c *Client) Execute(ctx context.Context, query string, variables map[string]interface{}, result interface{}) error { |
| 115 | + reqBody := graphQLRequest{ |
| 116 | + Query: query, |
| 117 | + Variables: variables, |
| 118 | + } |
| 119 | + |
| 120 | + body, err := json.Marshal(reqBody) |
| 121 | + if err != nil { |
| 122 | + return fmt.Errorf("failed to marshal request: %w", err) |
| 123 | + } |
| 124 | + |
| 125 | + req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.endpoint, bytes.NewReader(body)) |
| 126 | + if err != nil { |
| 127 | + return fmt.Errorf("failed to create request: %w", err) |
| 128 | + } |
| 129 | + |
| 130 | + req.Header.Set("Content-Type", "application/json") |
| 131 | + req.Header.Set("Accept", "application/json") |
| 132 | + |
| 133 | + for key, value := range c.headers { |
| 134 | + req.Header.Set(key, value) |
| 135 | + } |
| 136 | + |
| 137 | + resp, err := c.httpClient.Do(req) |
| 138 | + if err != nil { |
| 139 | + return fmt.Errorf("failed to execute request: %w", err) |
| 140 | + } |
| 141 | + defer resp.Body.Close() |
| 142 | + |
| 143 | + respBody, err := io.ReadAll(resp.Body) |
| 144 | + if err != nil { |
| 145 | + return fmt.Errorf("failed to read response body: %w", err) |
| 146 | + } |
| 147 | + |
| 148 | + if resp.StatusCode != http.StatusOK { |
| 149 | + return fmt.Errorf("unexpected status code: %d, body: %s", resp.StatusCode, string(respBody)) |
| 150 | + } |
| 151 | + |
| 152 | + var gqlResp graphQLResponse |
| 153 | + if err := json.Unmarshal(respBody, &gqlResp); err != nil { |
| 154 | + return fmt.Errorf("failed to unmarshal response: %w", err) |
| 155 | + } |
| 156 | + |
| 157 | + if len(gqlResp.Errors) > 0 { |
| 158 | + return GraphQLErrors(gqlResp.Errors) |
| 159 | + } |
| 160 | + |
| 161 | + if result != nil && gqlResp.Data != nil { |
| 162 | + if err := json.Unmarshal(gqlResp.Data, result); err != nil { |
| 163 | + return fmt.Errorf("failed to unmarshal data: %w", err) |
| 164 | + } |
| 165 | + } |
| 166 | + |
| 167 | + return nil |
| 168 | +} |
| 169 | + |
| 170 | +// RawQuery executes a GraphQL query and returns the raw JSON "data" payload. |
| 171 | +func (c *Client) RawQuery(ctx context.Context, query string, variables map[string]interface{}) (json.RawMessage, error) { |
| 172 | + var result struct { |
| 173 | + Data json.RawMessage `json:"data"` |
| 174 | + } |
| 175 | + |
| 176 | + if err := c.Execute(ctx, query, variables, &result); err != nil { |
| 177 | + return nil, err |
| 178 | + } |
| 179 | + |
| 180 | + return result.Data, nil |
| 181 | +} |
0 commit comments