Skip to content

Commit

Permalink
added method to execute queries already pre-built (shurcooL#32)
Browse files Browse the repository at this point in the history
* added method to execute queries already pre-built
  • Loading branch information
dbarrosop authored Apr 25, 2022
1 parent 281df85 commit 3d809b3
Showing 1 changed file with 16 additions and 1 deletion.
17 changes: 16 additions & 1 deletion graphql.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,11 @@ func (c *Client) buildAndRequest(ctx context.Context, op operationType, v interf
return nil, nil, nil, Errors{newError(ErrGraphQLEncode, err)}
}

return c.request(ctx, query, variables, options...)
}

// Request the common method that send graphql request
func (c *Client) request(ctx context.Context, query string, variables map[string]interface{}, options ...Option) (*json.RawMessage, *http.Response, io.Reader, Errors) {
in := struct {
Query string `json:"query"`
Variables map[string]interface{} `json:"variables,omitempty"`
Expand All @@ -118,7 +123,7 @@ func (c *Client) buildAndRequest(ctx context.Context, op operationType, v interf
Variables: variables,
}
var buf bytes.Buffer
err = json.NewEncoder(&buf).Encode(in)
err := json.NewEncoder(&buf).Encode(in)
if err != nil {
return nil, nil, nil, Errors{newError(ErrGraphQLEncode, err)}
}
Expand Down Expand Up @@ -231,7 +236,17 @@ func (c *Client) doRaw(ctx context.Context, op operationType, v interface{}, var
// do executes a single GraphQL operation and unmarshal json.
func (c *Client) do(ctx context.Context, op operationType, v interface{}, variables map[string]interface{}, options ...Option) error {
data, resp, respBuf, errs := c.buildAndRequest(ctx, op, v, variables, options...)
return c.processResponse(v, data, resp, respBuf, errs)
}

// Executes a pre-built query and unmarshals the response into v. Unlike the Query method you have to specify in the query the
// fields that you want to receive as they are not inferred from v. This method is useful if you need to build the query dynamically.
func (c *Client) Exec(ctx context.Context, query string, v interface{}, variables map[string]interface{}, options ...Option) error {
data, resp, respBuf, errs := c.request(ctx, query, variables, options...)
return c.processResponse(v, data, resp, respBuf, errs)
}

func (c *Client) processResponse(v interface{}, data *json.RawMessage, resp *http.Response, respBuf io.Reader, errs Errors) error {
if data != nil {
err := jsonutil.UnmarshalGraphQL(*data, v)
if err != nil {
Expand Down

0 comments on commit 3d809b3

Please sign in to comment.