From 3d809b3b2ae974c1e7fa5cc317c4d7cdee646beb Mon Sep 17 00:00:00 2001 From: David Barroso Date: Mon, 25 Apr 2022 07:13:50 +0200 Subject: [PATCH] added method to execute queries already pre-built (#32) * added method to execute queries already pre-built --- graphql.go | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/graphql.go b/graphql.go index 3eb8142..55e8b1a 100644 --- a/graphql.go +++ b/graphql.go @@ -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"` @@ -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)} } @@ -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 {