move a bunch of the logic from generated into client

This commit is contained in:
Ben Kraft
2019-12-25 16:26:32 -05:00
parent 9d4b5559f4
commit 4d880a701e
7 changed files with 99 additions and 99 deletions
+2 -6
View File
@@ -40,8 +40,6 @@ type OperationParams struct {
OperationName string
// The documentation for the operation, from GraphQL.
OperationDoc string
// The endpoint to which to send queries.
Endpoint string
// The body of the operation to send.
Operation string
}
@@ -89,16 +87,15 @@ func Generate(specFilename, schemaFilename, generatedFilename string) error {
if generatedFilename == "-" {
out = os.Stdout
} else {
out, err = os.OpenFile(generatedFilename, os.O_RDWR|os.O_CREATE, 0755)
out, err = os.OpenFile(generatedFilename, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0755)
if err != nil {
return fmt.Errorf("could not open generated file %v: %v",
generatedFilename, err)
}
}
// TODO: configure these
// TODO: configure this
packageName := "example"
endpoint := "https://api.github.com/graphql"
// TODO: this should probably get factored out
operations := make([]OperationParams, len(document.Operations))
@@ -125,7 +122,6 @@ func Generate(specFilename, schemaFilename, generatedFilename string) error {
ResponseName: operation.Name + "Response",
ResponseType: typeFor(operation, schema),
Endpoint: endpoint,
// The newline just makes it format a little nicer
Operation: "\n" + builder.String(),
}
+5 -45
View File
@@ -2,57 +2,17 @@ package {{.PackageName}}
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strings"
"github.com/vektah/gqlparser/gqlerror"
"github.com/Khan/genql/graphql"
)
{{range .Operations}}
type {{.ResponseName}} = {{.ResponseType}}
// {{.OperationDoc}}
func {{.OperationName}}(ctx context.Context) (*{{.ResponseName}}, error) {
req, err := http.NewRequest(
http.MethodPost,
`{{.Endpoint}}`,
strings.NewReader(`{{.Operation}}`))
if err != nil {
return nil, err
}
req = req.WithContext(ctx)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("returned error %v: %v", resp.Status, string(body))
}
var retval struct {
Data {{.ResponseName}} `json:"data"`
Errors gqlerror.List `json:"errors"`
}
err = json.Unmarshal(body, &retval)
if err != nil {
return nil, err
}
if len(retval.Errors) > 0 {
return nil, retval.Errors
}
return &retval.Data, nil
func {{.OperationName}}(ctx context.Context, client *graphql.Client) (*{{.ResponseName}}, error) {
var retval {{.ResponseName}}
err := client.MakeRequest(ctx, `{{.Operation}}`, &retval)
return &retval, err
}
{{end}}