Skip to content

Commit

Permalink
Add option to query the merchant center api
Browse files Browse the repository at this point in the history
  • Loading branch information
mvantellingen committed Jul 14, 2020
1 parent f2bd4f1 commit ef6c7eb
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
4 changes: 4 additions & 0 deletions commercetools/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,9 @@ func getConfigValue(value string, envName string) string {
}
return os.Getenv(envName)
}
func (c *Client) Endpoints() ClientEndpoints {
return c.endpoints
}

// Get accomodates get requests tot the CommerceTools platform.
func (c *Client) Get(ctx context.Context, endpoint string, queryParams url.Values, output interface{}) error {
Expand Down Expand Up @@ -287,6 +290,7 @@ func (c *Client) doRequest(ctx context.Context, method string, endpoint string,
}

func (c *Client) getResponse(ctx context.Context, method string, url string, params url.Values, data io.Reader) (*http.Response, error) {
fmt.Println(url)
req, err := http.NewRequestWithContext(ctx, method, url, data)
if err != nil {
return nil, errors.Wrap(err, "Creating new request")
Expand Down
18 changes: 15 additions & 3 deletions commercetools/client_graphql.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ func (client *Client) NewGraphQLQuery(query string) *GraphQLQuery {

queryObject := GraphQLQuery{
client: client,
endpoint: fmt.Sprintf("%s/%s/graphql", client.url, client.projectKey),
endpoint: fmt.Sprintf("%s/%s/graphql", client.Endpoints().API, client.projectKey),
query: query,
}

Expand All @@ -40,24 +40,36 @@ func (gql *GraphQLQuery) Bind(key string, value interface{}) {
gql.vars[key] = value
}

type GraphQLOption func(o *GraphQLQuery)

func (gql *GraphQLQuery) ForMerchantCenter() GraphQLOption {
return func(o *GraphQLQuery) {
o.endpoint = fmt.Sprintf("%s/graphql", o.client.Endpoints().MerchantCenterAPI)
}
}

// Execute the GraphQL query
func (gql *GraphQLQuery) Execute(respData interface{}) error {
func (gql *GraphQLQuery) Execute(respData interface{}, opts ...GraphQLOption) error {
var body bytes.Buffer

requestObj := GraphQLRequest{
Query: gql.query,
Variables: &gql.vars,
}

for _, opt := range opts {
opt(gql)
}

if err := json.NewEncoder(&body).Encode(requestObj); err != nil {
return errors.Wrap(err, "encode body")
}
ctx := context.TODO()
resp, err := gql.client.getResponse(ctx, "POST", gql.endpoint, nil, &body)
defer resp.Body.Close()
if err != nil {
return err
}
defer resp.Body.Close()

return gql.processResponse(resp, respData)
}
Expand Down

0 comments on commit ef6c7eb

Please sign in to comment.